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