Home > OS >  Macro directive sequence in C
Macro directive sequence in C

Time:08-08

I'm reading C Programming: A Modern Approach. In Ch14 exercise #11:

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

The output is N is undefined, while I expected it to be N is 100. However, if we move the content of function f into main, it works as expected:

#include <stdio.h>

#define N 100

void f(void);

int main(void) {
#if defined(N)
    printf("N is %d\n", N);
#else
    printf("N is undefined\n");
#endif

#ifdef N
#undef N
#endif
    return 0;
}

The output is N is 100. Why so? Why the preprocessor can retroactively apply the #undef into f()? Thanks.

CodePudding user response:

Macro preprocessing takes place before other steps of compilation, let alone runtime evaluation. It's line-by-line, you can think of it as a text replacement. So, when you write #undef N in main(), then you already undefine the macro; it'll not be defined in f().

Of course, if you check it before undefining it (but after defining it as 100), then it'll have the value you'd expect.

  • Related