Static scoping in C/C++
In the following code, 2 is printed.
int x = 1;
int f(int y)
{
return x;
}
int main() {
x = 2;
printf("%d", f(0));
}
How is it happening if we have static scoping in C? Why isn't 1 printed?
Printing 2 in this case isn't a dynamic scoping, is it?
I thought that in static scoping it should take the nearest x to the function definition.
It does take the nearest x , but since you only have one x it doesn't really matter.
If you change the code to
int x = 1;
int f(int y)
{
return x ;
}
int main() {
int x=2;
printf("%d", f(0));
}
so you have 2 x , the global one and the local one in main you will see 1 getting printed.
The scoping is moot here since you have not declared an x locally that would have otherwise shadowed the global x .
2 is printed.
x is assigned in main to 2 immediately before f is called with the parameter 0 .
(Conceptually int x = 1; is ran before main is entered.)
It is the way the compiler generates the assembly/machine code.
So if you wanted a different X in the main-function scope, you should have made a new object, like in the answer by nwp.
链接地址: http://www.djcxy.com/p/82492.html上一篇: 函数作用域结束后内存中局部变量的持久性?
下一篇: C / C ++中的静态作用域
