Skip to main content
Engineering LibreTexts

1.2.2: Understanding Preprocessing- Conditional Compilation

  • Page ID
    29005
  • Conditional Compilation

    Conditional Compilation directives are type of directives which helps to compile a specific portion of the program or to skip compilation of some specific part of the program based on some conditions. This can be done with the help of several preprocessing commands  #if, #ifdef, #ifndef, #if, #endif, #else and #elif. (#ifdef - is 'if defined', and #ifndef - is 'if not define')

    Using these commands is relatively simple. The #ifdef directive says, "If this is defined" - in the following code it says, "If the macro TABLE_SIZE is defined, then declare an integer array called table, that is TABLE_SIZE in length". If TABLE_SIZE has not been defined, then the integer array table will NOT be defined.

    #ifdef TABLE_SIZE
    int table[TABLE_SIZE];
    #endif  

    The #if, #ifdef, and #ifndef directives MUST end with an #endif statement, otherwise the condition continues until one is found.

    A little more complex example is shown below:

    #include <iostream>
    
    #define TABLE_SIZE 500
    
    #if TABLE_SIZE > 200
    #undef TABLE_SIZE
    #define TABLE_SIZE 200
     
    #elif TABLE_SIZE < 50
    #undef TABLE_SIZE
    #define TABLE_SIZE 50
     
    #else
    #undef TABLE_SIZE
    #define TABLE_SIZE 100
    #endif
     
    int table[TABLE_SIZE];
    
    std::cout << "The table will hold: " << TABLE_SIZE << " values" << std::endl;

    So, if the macro TABLE_SIZE is greater than 200, the macro is undefined (by the #undef directive), the defined once more with a value of 200. Else if the macro has a value less than 50 it is undefined, and redefined with a value of 50. Otherwise it is set to 100.

    Try changing the value of TABLE_SIZE in the #define statement at the top, and see if you can predict the correct output.

     

    Adapted from: "C/C++ Preprocessors" by Harsh AgarwalGeeks for Geeks is licensed under CC BY-SA 4.0