103

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    You can nest conditionals, and you can call one macro from another but you can't nest macros directly, e.g. `#define AAA #define XXX` - it won't work correctly. – SF. Jul 13 '11 at 12:46
  • 2
    Since [a C question](http://stackoverflow.com/q/38963852/827263) was just closed as a duplicate of this one, I'll point out that rules for the C and C++ preprocessor are the same, at least as far as this question is concerned. – Keith Thompson Aug 15 '16 at 22:44

3 Answers3

132

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 --------|
Zachi Shtain
  • 826
  • 1
  • 13
  • 31
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
64

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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
0

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

Good luck!

bert-jan
  • 958
  • 4
  • 15