Show: Delphi C++
Display Preferences

IF directive (Delphi)

From RAD Studio
Jump to: navigation, search

Go Up to Delphi Compiler Directives (List) Index


Conditional compilation


{$IF expression}


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 Defined and Declared functions.

For example,

const LibVersion = 2.1;
  {$IF Defined(MY_DEFINE) and (LibVersion > 2.0) }
    Writeln(2);  // this code does not execute
  {$IF Defined(MY_DEFINE) }
    Writeln(3);  // this code executes
  {$ELSEIF LibVersion > 2.0}
    Writeln(4);  // this code does not execute
  {$ELSEIF LibVersion = 2.0}
    Writeln(5);  // this code does not execute
    Writeln;  // this code does not execute
  {$IF Declared(Test)}
    Writeln('Success'); // successful

The special Defined and Declared functions 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');

You can use the FireMonkeyVersion constant (defined in FMX.Types.pas and equal to 16.1 at the XE2 Update 2 release) in an IF directive. To identify and separate FireMonkey code that is for any version higher than 16.0, surround the code with the following conditional directive:

  {$IF Declared(FireMonkeyVersion) and (FireMonkeyVersion > 16.0)}

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}

$IF supports evaluation of typed constants, but the compiler does not 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

See Also

Personal tools
RAD Studio 10.2 Tokyo
In other languages
Previous Versions