xHarbour Reference Documentation > Preprocessor Reference |
Compile a section of code based on a condition.
#if <condition1> <statements1> [ #elif <conditionN> <statmentsN> ] [ #else <statments> ] #endif
The #if..#elif..#else..#endif directives are used for conditional compilation. They work analogous to the IF..ELSEIF..ELSE..ENDIF statements, but are resolved by the preprocessor, rather than the compiler. In contrast to the #ifdef and #ifndef directives, which test only the presence or absence of #define constants, #if allows for testing the values of such constants and comparing them with other values. In addition, multiple conditions can be formulated using #if..#elif. When the #else directive is used, it must be the last one, followed by #endif.
The statements following the first condition that resolves to True is included in the preprocessor output. All other statements are discarded. That means, even if multiple conditions are True, only one of the code statements appears in the preprocessor output. When all conditions are False, the statements following the #else directive, if present, are used.
The following rules are applied by the preprocessor to evaluate a condition:
1. | A numeric literal <> 0 yields True, while exact zero yields False. |
2. | The logical literal .T. is True, .F. is False. |
3. | #define constants with no associated value yield False. |
4. | The literal value NIL yields False. |
5. | Other literal values cannot be used and result in a compile error. |
6. | Numeric values can be compared using the comparison operators !=, #, >, >=, =, ==, =< and <. The True/False result of the comparison is evaluated by the preprocessor. |
See also: | #define, #ifdef, #ifndef |
Category: | Preprocessor directives , xHarbour extensions |
// The example demonstrates how the same source code file can be // compiled for different program versions. Depending on the #define // constant MAKE_VERSION, differen initilization routines are called. #define FULL_VERSION 3 #define RESTRICTED_VERSION 2 #define DEMO_VERSION 1 #define MAKE_VERSION RESTRICTED_VERSION PROCEDURE Main #if MAKE_VERSION > RESTRICTED_VERSION InitFullPackage() #elif MAKE_VERSION > DEMO_VERSION InitRestrictedPackage() #else InitDemoPackage() #endif ? "Common code for all packages" RETURN
http://www.xHarbour.com