#include <stdio.h>
int main () {
int i = 3;
printf("%d\n", i);
if (i == 3) {
i = i + 1;
int i = 6;
printf("%d\n", i);
i = i + 1;
}
if (i == 3) {
printf("%d\n", i);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么4和7消失了?
当我运行代码时,他们只打印输出3和6?
这里没有"消失",这是因为,内部范围优先于具有重叠范围的标识符的外部范围.
引用C11,章节§6.2.1(强调我的)
[...]如果标识符指定同一名称空间中的两个不同实体,则范围可能会重叠.如果是这样,一个实体(内部范围)的范围将严格地在另一个实体(外部范围)的范围之前结束.在内部范围内,标识符指定在内部范围内声明的实体; 在外部作用域中声明的实体在内部作用域内隐藏(并且不可见).
所以,在你的情况下,(按照评论)
#include <stdio.h>
int main (void) { //note the correct signature
int i = 3; //outer scope of i
printf("%d\n", i);
if (i == 3) {
i = i + 1; //this happens in "outer" scope, i value changed...
//---------------------> |-----inner scope starts, outer scope gets hidden
int i = 6; // |
printf("%d\n", i); // |
i = i + 1; // |
}//------------------------> |-----inner scope ends, outer scope resumes
if (i == 3) { // hey. look , other scope is back!!!
printf("%d\n", i);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)