c - C 中宏的作用域?

标签 c c-preprocessor

如何评估这些宏?

# define i 20
void fun();

int main(){
  printf("%d",i);
  fun();
  printf("%d",i);
  return 0;
}

void fun(){
  #undef i
  #define i 30
}

输出为 2020,但是,

# define i 20
void fun(){
  #undef i
  #define i 30
}

int main(){
  printf("%d",i);
  fun();
  printf("%d",i);
  return 0;
}

输出为 3030。 请解释。谢谢。

最佳答案

C 预处理器的工作自上而下 与函数调用无关。无论该宏定义在哪个文件中,它都从该点(行)开始生效,直到相应的 undef 或直到翻译单元结束。

所以,你的代码会变成,

# define i 20
               // from now on, all token i should become 20
void fun();
int main()
{
  printf("%d",i);   // printf("%d",20);
  fun();
  printf("%d",i);   // printf("%d",20);
  return 0;
}
void fun()
{
#undef i
              // from now on, forget token i
#define i 30
              // from now on, all token i should become 30
}

你的第二个代码会变成,

# define i 20
               // from now on, all token i should become 20
void fun()
{
#undef i
               // from now on, forget i
#define i 30
               // from now on, all token i should become 30
}
int main()
{
  printf("%d",i);    //  printf("%d",30);
  fun();
  printf("%d",i);    // printf("%d",30);
  return 0;
}

关于c - C 中宏的作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17349387/

相关文章:

c++ - C 预处理器替换和连接

c - C宏中两个相邻的井号是什么意思?

c - 如何找到具体实现定义的值(value)?

c++ - 如何通过预处理器指令检查程序是否需要 Visual C++ 中的预编译头文件?

c - API和系统调用的区别

c - Tabular Recta 表未正确生成

c++ - clang on 64bit compile error with -m32

c - 使用 MASM 生成目标文件并将它们与 MSVC 目标文件链接

c - 嵌入式 C 时序问题

c - 如何强制预处理器在 C/C++ 中使用所需的数据类型?