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

user707549 picture user707549 · Jul 13, 2011 · Viewed 37.3k times · Source

I have a question about Pre-processor 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?

Answer

Armen Tsirunyan picture Armen Tsirunyan · Jul 13, 2011

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

e.g.

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