c++中变量的作用域和优先级
the scope and priority of variable in c++
谁能给我解释一下为什么结果是 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;
}
内部 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
}
因此
f(1) + f(2) // 1 + 1 == 2
这都是关于变量 阴影。
函数 f
中最内层的 x
隐藏了该函数中的自动 x
。所以那个函数相当于
int f(int){
auto x = 1;
return x;
}
此外请注意,我的缩略版 shadows 中的 x
是全局范围的。
函数f
进一步简写为
int f(int){
return 1;
}
现在程序输出应该很明显了。
其实这个函数
int f(int i){
auto x = 1;
{
static auto x = 0;
x += i;
}
return x;
}
可以改写成
int f(int i){
auto x = 1;
return x;
}
因为在这个块作用域
声明的静态变量x
{
static auto x = 0;
x += i;
}
不在块外使用,不影响函数的返回值。此代码块的唯一副作用是具有未定义行为的静态有符号整数变量 x
可能溢出。
所以两个函数调用 f(1)
和 f(2)
returns 1
结果表达式 f(1) + f(2)
产生 2
.
程序中声明了三个变量x
。全局名称中的第一个space
auto x = 0;
函数f
的最外层块中的第二个隐藏全局名称space中变量x
的声明。
auto x = 1;
而第三个是在函数 f
的内部块中声明的
{
static auto x = 0;
x += i;
}
在此内部块之外不可见。
谁能给我解释一下为什么结果是 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;
}
内部 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
}
因此
f(1) + f(2) // 1 + 1 == 2
这都是关于变量 阴影。
函数 f
中最内层的 x
隐藏了该函数中的自动 x
。所以那个函数相当于
int f(int){
auto x = 1;
return x;
}
此外请注意,我的缩略版 shadows 中的 x
是全局范围的。
函数f
进一步简写为
int f(int){
return 1;
}
现在程序输出应该很明显了。
其实这个函数
int f(int i){
auto x = 1;
{
static auto x = 0;
x += i;
}
return x;
}
可以改写成
int f(int i){
auto x = 1;
return x;
}
因为在这个块作用域
声明的静态变量x
{
static auto x = 0;
x += i;
}
不在块外使用,不影响函数的返回值。此代码块的唯一副作用是具有未定义行为的静态有符号整数变量 x
可能溢出。
所以两个函数调用 f(1)
和 f(2)
returns 1
结果表达式 f(1) + f(2)
产生 2
.
程序中声明了三个变量x
。全局名称中的第一个space
auto x = 0;
函数f
的最外层块中的第二个隐藏全局名称space中变量x
的声明。
auto x = 1;
而第三个是在函数 f
的内部块中声明的{
static auto x = 0;
x += i;
}
在此内部块之外不可见。