如果预处理器指令可以嵌套在 C + + 中吗?

我有一个关于 c + + 中预处理器指令的问题:

例如:

#ifndef QUESTION


//some code here


#ifndef QUESTION


//some code here


#endif


#endif

我们可以这样使用它吗? C + + 编译器能否以正确的方式匹配 ifndefendif

45973 次浏览

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

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.

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

Good luck!