Search code examples
c++c-preprocessorpreprocessor-directive

Can #if pre-processor directives be nested in C++?


I have a question about preprocessor directives in C++:

For example:

#ifndef QUESTION

// Some code here

#ifndef QUESTION

// Some code here

#endif

#endif

Can we use it in this way, and can the C++ compiler match the ifndef and endif in the right way?


Solution

  • Yes, we can. The #endif statement matches the previous #if, #ifdef, #ifndef, etc. for which there hasn't been a corresponding #endif.

    For example,

    #if  ----------|
    #if  -----|    |
    #endif ---|    |
    #endif --------|