#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
In this what is the role of #ifdef
and #ifndef
, and what's the output?
Text inside an ifdef/endif
or ifndef/endif
pair will be left in or removed by the pre-processor depending on the condition. ifdef
means "if the following is defined" while ifndef
means "if the following is not defined".
So:
#define one 0
#ifdef one
printf("one is defined ");
#endif
#ifndef one
printf("one is not defined ");
#endif
is equivalent to:
printf("one is defined ");
since one
is defined so the ifdef
is true and the ifndef
is false. It doesn't matter what it's defined as. A similar (better in my opinion) piece of code to that would be:
#define one 0
#ifdef one
printf("one is defined ");
#else
printf("one is not defined ");
#endif
since that specifies the intent more clearly in this particular situation.
In your particular case, the text after the ifdef
is not removed since one
is defined. The text after the ifndef
is removed for the same reason. There will need to be two closing endif
lines at some point and the first will cause lines to start being included again, as follows:
#define one 0
+--- #ifdef one
| printf("one is defined "); // Everything in here is included.
| +- #ifndef one
| | printf("one is not defined "); // Everything in here is excluded.
| | :
| +- #endif
| : // Everything in here is included again.
+--- #endif