此问题已在此处有答案:
Why is using the function name as a function pointer equivalent to applying the address-of operator to the function name?(3个答案)
11个月前关闭。
考虑一个普通的代码:
#include <stdio.h>
int x;
int func(int a){
x++;
return a;
}
int main(){
int a = 1;
int n = func(a);
printf("x = %d, n = %d", x, n);
return 0;
}
它将按预期打印x = 1, n = 1
。
但是如果我稍微编辑代码如下:
#include <stdio.h>
int x;
int func(int a){
x++;
return a;
}
int main(){
int a = 1;
int n = func;
printf("x = %d, n = %d", x, n);
return 0;
}
由于函数编写不正确,编译器不会报告错误,而是打印x = 0, n = 4199760
。
程序怎么了?
函数的名字有什么特殊的含义吗?
谢谢大家。
1条答案
按热度按时间q5iwbnjs1#
是的。在第二次迭代中,行:
基本上是声明“检索函数“func”所在的内存地址,并将该值存储到变量“n”中。这行代码没有调用你的函数。因此,变量“x”没有被更新,并且保持为值“0”,这将为您提供您看到的输出。而且,如果你碰巧再次运行你的程序,你的函数的内存地址的值可能会改变,你可能会看到一个不同的值打印出来。
希望这能澄清一些事情。
问候。