RAD Studio (Common)
ContentsIndex
PreviousUpNext
IF directive (Delphi)
Type  
Conditional compilation  
Syntax  
{$IF expression}  

Remarks 

Compiles the Delphi source code that follows it if expression is true. expression must conform to Delphi syntax and return a Boolean value; it may contain declared constants, constant expressions, and the functions Defined and Declared. 

For example,

{$DEFINE CLX}
    const LibVersion = 2.1;
    {$IF Defined(CLX) and (LibVersion > 2.0) }
      ...  // this code executes
    {$ELSE}
      ...  // this code doesn't execute
    {$IFEND}
    {$IF Defined(CLX) }
      ...  // this code executes
    {$ELSEIF LibVersion > 2.0}
      ...  // this code doesn't execute
    {$ELSEIF LibVersion = 2.0}
      ...  // this code doesn't execute
    {$ELSE}
      ...  // this code doesn't execute
    {$IFEND}
    {$IF Declared(Test)}
      ... // successful
    {$IFEND}

The special functions Defined and Declared are available only within $IF and $ELSEIF blocks. Defined returns true if the argument passed to it is a defined conditional symbol. Declared returns true if the argument passed to it is a valid declared Delphi identifier visible within the current scope. 

If the identifiers referenced in the conditional expression do not exist, the conditional expression will be evaluated as false:

{$IF NoSuchVariable > 5}
     WriteLn('This line doesn''t compile');
    {$IFEND}

The $IF and $ELSEIF directives are terminated with $IFEND, unlike other conditional directives that use the $ENDIF terminator. This allows you to hide $IF blocks from earlier versions of the compiler (which do not support $IF or $ELSEIF) by nesting them within old-style $IFDEF blocks. For example, the following construction would not cause a compilation error:

     {$UNDEF NewEdition}
         {$IFDEF NewEdition}
           {$IF LibVersion > 2.0}
             ...
           {$IFEND}
         {$ENDIF}

$IF supports evaluation of typed constants, but the compiler doesn't allow typed constants within constant expressions. As a result,

const Test: Integer = 5;
    {$IF SizeOf(Test) > 2}
    ...

is valid, while

const Test: Integer = 5;
    {$IF Test > 2 }         // error
    ...

generates a compilation error. 

If your code needs to be portable between various versions of Delphi, or platforms (such as .NET), you will need to test whether or not this directive is supported by the compiler. You can surround your code with the following directives:

$IFDEF conditionalexpressions
    .          // code including IF directive
    .          // only executes if supported
    $ENDIF

Note: To test if code is being compiled on the .NET platform, use the identifier CLR, for example, {$IF NOT DEFINED(CLR)}.

Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!