声明与全局,局部和静态同名的变量 [英] declaration of variables with same name as global,local and static
本文介绍了声明与全局,局部和静态同名的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码片段,我必须分析输出内容:
I have the following code snippet and I have to analyse what the output will be:
#include <stdio.h>
void f(int d);
int a = 1, b = 2, c = 3, d = 4;
int main(){
int a = 5, c = 6;
f(a);
f(b);
f(c);
printf("%d %d %d %d\n",a,b,c,d);
return 0;
}
void f(int d){
static int a = 0;
a = a + 7;
b = a + d;
c++;
d--;
printf("%d %d %d %d\n",a,b,c,d);
}
我得到的输出如下:
7 12 4 4
15 26 5 11
21 27 6 5
5 27 6 4
这真的让我感到困惑。我注意到,在所有3个函数调用中,全局声明的 a
都遭受分配,并且在 printf()
中, code> main()主体在 main()
中声明的 a
是打印。但是,我不确定其余变量的行为。
This really baffled me. I noticed that in all 3 function calls the globally declared a
suffers the assignment and that in the printf()
from main()
body the a
declared in main()
is printed. However, I am not sure about the behaviour of the rest of the variables. Is this undefined behaviour or it actually makes sense?
推荐答案
int a = 1,b = 2,是真的吗? c = 3,d = 4;
--->全局变量
int main(){
int a = 5, c = 6; ---> Shadows the global `a` and `c`
....
void f(int d){
static int a = 0; ---> local static variable visible only inside `f`
...
这篇关于声明与全局,局部和静态同名的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文