Kai*_*xin 7 c++ scope declaration
任何人都可以向我解释为什么结果是 2,x 正在使用哪个以及为什么。
auto x = 0;
int f(int i){
auto x = 1;
{
static auto x = 0;
x += i;
}
return x;
}
int main() {
cout << f(1) + f(2) <<endl;// result 2
return 0;
}
Run Code Online (Sandbox Code Playgroud)
内部x遮蔽外部,但突变仅适用于最内部的范围
int f(int i){
auto x = 1; // consider this "x1"
{
static auto x = 0; // this is "x2"
x += i; // mutates "x2" but not "x1"
}
return x; // return "x1" which is still 1
}
Run Code Online (Sandbox Code Playgroud)
所以
f(1) + f(2) // 1 + 1 == 2
Run Code Online (Sandbox Code Playgroud)
这都是关于变量阴影的。
最里面x的功能f是隐藏该功能中的自动x功能。所以这个函数等价于
int f(int){
auto x = 1;
return x;
}
Run Code Online (Sandbox Code Playgroud)
注意此外建议,x在我的删节版的影子了一个在全局范围内。
该函数f进一步缩写为
int f(int){
return 1;
}
Run Code Online (Sandbox Code Playgroud)
现在程序输出应该很明显了。
其实这个功能
int f(int i){
auto x = 1;
{
static auto x = 0;
x += i;
}
return x;
}
Run Code Online (Sandbox Code Playgroud)
可以重写为
int f(int i){
auto x = 1;
return x;
}
Run Code Online (Sandbox Code Playgroud)
因为x在这个块作用域中声明的静态变量
{
static auto x = 0;
x += i;
}
Run Code Online (Sandbox Code Playgroud)
不在块外使用,不影响函数的返回值。此代码块的唯一副作用是x具有未定义行为的静态带符号整数变量可能溢出。
所以这两个函数都调用f(1)并 f(2)返回1,结果表达式f(1) + f(2)yield 2。
在程序中声明了三个变量x。全局命名空间中的第一个
auto x = 0;
Run Code Online (Sandbox Code Playgroud)
函数最外层块中的第二个块f,隐藏x全局命名空间中的变量声明。
auto x = 1;
Run Code Online (Sandbox Code Playgroud)
第三个在函数 f 的内部块中声明
{
static auto x = 0;
x += i;
}
Run Code Online (Sandbox Code Playgroud)
在这个内部块之外是不可见的。