这个问题是在一次采访中提出的,我完全不知道输出有何不同。以下是问题
#define a 10
void foo();
int main()
{
printf("%d..",a);
foo();
printf("%d",a);
}
void foo()
{
#undef a
#define a 50
}
这给了我 10..10 作为输出,而
#define a 10
void foo()
{
#undef a
#define a 50
}
int main()
{
printf("%d..",a);
foo();
printf("%d",a);
}
这给了我 50..50 作为输出。 请解释一下。谢谢
发生这种情况是因为预处理替换甚至在实际编译之前发生,它不会在运行时发生。
#define
指令的值(或定义(根据编写的代码语法有效,而不是根据调用约定有效。
所以,在第一种情况下
#define a 10 // a is defined here
void foo();
int main()
{
printf("%d..",a); // a == 10, substitution happens
foo(); //nothing useful here
printf("%d",a); // a == 10, substitution happens
}
void foo()
{
#undef a // a vanished
#define a 50 // a is redefined as 50
} // a will be substituted to 50 hereon, is used
然而,在第二种情况下
#define a 10 // a is defined here
void foo()
{
#undef a // a vanished
#define a 50 // a is redefined as 50
} // a will be substituted to 50 hereon, is used
int main()
{
printf("%d..",a); // a == 50, substitution happens
foo(); // nothing useful here
printf("%d",a); // a == 50, substitution happens
}
预处理器在编译代码之前按照预处理器指令在文件中出现的顺序运行,而不是按照文件中定义的函数顺序运行。