Aym*_*nis 4 c global-variables local-variables
我有点困惑这个代码结果:
#include <stdio.h>
int g;
void afunc(int x)
{
g = x; /* this sets the global to whatever x is */
}
int main(void)
{
int g = 10; /* Local g is now 10 */
afunc(20); /* but this function will set it to 20 */
printf("%d\n", g); /* so this will print "20" */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么结果是10不是20?
局部变量g影响全局g.
如果你想要printf()显示20,你必须g使用你想要打印的全局变量的声明来遮蔽你的局部变量:
int main(void)
{
int g = 10; /* Local g is now 10 */
afunc(20); /* Set global g to 20 */
printf("%d\n", g); /* Print local g, "10" */
{
extern int g; /* Use global g */
printf("%d\n", g); /* Print global g, "20" */
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)