xHarbour Reference Documentation > Preprocessor Reference xHarbour Developers Network  

#if

Compile a section of code based on a condition.

Syntax

  #if <condition1>
   <statements1>
[ #elif <conditionN>
   <statmentsN> ]
[ #else
   <statments>  ]
  #endif

Arguments

<condition1> .. <conditionN>
<condition> is one or more logical conditions that are resolved by the preprocessor. Conditions are formulated using #define constants, numeric or logical literal values. A condition expression may include comparison operators.
<statements1> .. <statementsN>
<statements> is the program code to include in the preprocessor output when a condition is true.

Description

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.

Info

See also:#define, #ifdef, #ifndef
Category: Preprocessor directives , xHarbour extensions

Example

// 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

Copyright © 2006-2007 xHarbour.com Inc. All rights reserved.
http://www.xHarbour.com
Created by docmaker.exe