IF directive (Delphi)
Go Up to Delphi Compiler Directives (List) Index
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 Defined and Declared functions.
For example,
...
{$DEFINE MY_DEFINE}
const LibVersion = 2.1;
...
begin
...
{$IF Defined(MY_DEFINE) and (LibVersion > 2.0) }
Writeln(1);
{$ELSE}
Writeln(2); // this code does not execute
{$IFEND}
{$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
{$ELSE}
Writeln; // this code does not execute
{$IFEND}
{$IF Declared(Test)}
Writeln('Success'); // successful
{$IFEND}
...
end.
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');
{$IFEND}
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)}
...
{$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 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
{$ENDIF}