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

C++C PreprocessorPreprocessor Directive

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

Yes, you can nest #if/#endif blocks. Some C coding styles would tell you to write

#ifdef CONDITION1
# ifdef CONDITION2
# endif
#endif

using spaces to denote the level of nesting.

Solution 3 - C++

In your code, the #ifndef QUESTION section will be discarded unless you #undef QUESTION.

Good luck!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser707549View Question on Stackoverflow
Solution 1 - C++Armen TsirunyanView Answer on Stackoverflow
Solution 2 - C++Fred FooView Answer on Stackoverflow
Solution 3 - C++bert-janView Answer on Stackoverflow