当前位置: 动力学知识库 > 问答 > 编程问答 >

c - Why un-defining a macro takes effect before #undef is reached?

问题描述:

#include <stdio.h>

void f(void);

#define N 100

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

}

Sorry same question like before but little different. Here same code it writes N is undefined

#include <stdio.h>

void f(void);

#define N 100

int main(void)

{

#if defined(N)

printf("N is %d\n",N);

#else

printf("N is undefined\n");

#endif // defined

/**f();

#ifdef N

#undef N

#endif**/

return 0;

}

/**void f(void){

}**/

But if I write the definitions from the f function in main instead it prints the output N is 100. Why does this print occur and why the difference?

网友答案:

You have to separate in your mind two timelines:

  • The compiling timeline - i.e. things that happen as your program is being compiled, and
  • The running timeline - i.e. the things that happen as your program runs

These two timelines are independent of each other. The compiling timeline roughly corresponds to the textual order of your program, with some corrections for #include processing and macro expansions. The running timeline is decided by your program's control structures, function invocations, and so on.

Since these two timelines are independent, a point X in code that is reached before point Y during the compile timeline may very well be reached after point Y during the running timeline. Moreover, it may be reached multiple times - both before and after another point Y.

Now let's go back to your question. #defines and macros are expanded at compile time, so before and after refer exclusively to the compile timeline. When you place #undef in main, above your function f, the un-definition happens before the use of N, leading to the compile-time error. The running timeline, according to which the call of f happens before the un-definition has no relevance, because #defines are an exclusively compile-time construct.

分享给朋友:
您可能感兴趣的文章:
随机阅读: