C/C++ 中静态关键字的输出问题
Problem with Output with Static keyword in C/C++
根据我的推理,输出应该是 0456,但编译器显示 0415,我对其进行了一些调试,发现它以不同的方式针对两个“i”。
如果有人能解释其背后的原因,我将不胜感激。
谢谢 :)
#include <iostream>
using namespace std;
int main()
{
static int i;
for(int j = 0; j<2; j++)
{
cout << i++;
static int i = 4;
cout << i++;
}
return 0;
}
您应该期望输出如下:
- 循环传递 #1:打印
0
(top-level 块作用域 i
),然后是 4
(for 循环块作用域 i
)。
- 循环传递 #2:打印
1
(top-level 块作用域 i
),然后是 5
(for 循环块作用域 i
)。
因此0415
.
static int i; // declares i at block-scope; denote as (i1)
for(int j = 0; j<2; j++)
{ // enter nested block scope
cout << i++; // at this point, `i` local to current
// block scope is yet to be declared.
// thus, this refers to (i1)
static int i = 4; // this declares a local `i` (denote as (i2))
// which shadows (i1) henceforth
cout << i++; // this refers to (i2)
}
即使局部静态变量 i
的 lifetime 从第一次循环开始(第一次控制通过它的声明),这样它的声明就被跳过了第二遍,这不影响它的scope。
Block scope
The potential scope of a name declared in a block (compound statement) begins at the point of declaration and ends at the end of the block [...]
根据我的推理,输出应该是 0456,但编译器显示 0415,我对其进行了一些调试,发现它以不同的方式针对两个“i”。
如果有人能解释其背后的原因,我将不胜感激。 谢谢 :)
#include <iostream>
using namespace std;
int main()
{
static int i;
for(int j = 0; j<2; j++)
{
cout << i++;
static int i = 4;
cout << i++;
}
return 0;
}
您应该期望输出如下:
- 循环传递 #1:打印
0
(top-level 块作用域i
),然后是4
(for 循环块作用域i
)。 - 循环传递 #2:打印
1
(top-level 块作用域i
),然后是5
(for 循环块作用域i
)。
因此0415
.
static int i; // declares i at block-scope; denote as (i1)
for(int j = 0; j<2; j++)
{ // enter nested block scope
cout << i++; // at this point, `i` local to current
// block scope is yet to be declared.
// thus, this refers to (i1)
static int i = 4; // this declares a local `i` (denote as (i2))
// which shadows (i1) henceforth
cout << i++; // this refers to (i2)
}
即使局部静态变量 i
的 lifetime 从第一次循环开始(第一次控制通过它的声明),这样它的声明就被跳过了第二遍,这不影响它的scope。
Block scope
The potential scope of a name declared in a block (compound statement) begins at the point of declaration and ends at the end of the block [...]