Reputation: 5
#include <stdio.h>
#define N 100
void f(void);
int main(void)
{
f();
#ifdef N
#undef N
#endif
return 0;
}
void f(void){
#if defined(N)
printf("N is %d\n",N);
#else
printf("N is undefined\n");
#endif // defined
}
Why does this output print N
is undefined shouldn't it print N
is 100 because of the function call on f
before it reaches the undef that removes the value 100?
Upvotes: 0
Views: 67
Reputation: 19504
Preprocessor directives and macros are processed at a very early stage of compilation, they have no existence at runtime.
Running your code just through the preprocessor (cpp -P
-- warning: remove the #include
first) shows the actual C code that is being compiled.
void f(void);
int main(void)
{
f();
return 0;
}
void f(void){
printf("N is undefined\n");
}
As to why this expansion is chosen rather than the alternate message, consider these lines in your source.
#ifdef N
#undef N
#endif
Regardless of whether it's defined or not initially, it will not be defined after these lines are (pre-)processed.
Upvotes: 1