重新定义作用域内的变量
为什么以下代码在 g++ 下编译时没有任何警告或错误?我看到的问题是第一行中定义的变量 x 可以在 if 范围内访问,但尽管它再次被重新定义.
Why does the following code compiles, under g++, with out any warning or error? The problem I see is that the variable x defined in the first line is accessible inside the if scope but in spite that it's redefined again.
int main() {
int x = 5;
std::cout << x;
if (true) {
int x = 6;
std::cout << x;
}
}
推荐答案
根据C
-
C99 中的 6.2.1:
6.2.1 in C99:
如果声明标识符的声明符或类型说明符出现在块内或函数定义的参数声明列表内,则标识符具有块作用域,终止于关闭关联块的 }
If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the } that closes the associated block
...
如果词法相同的标识符的外部声明存在于同一名称空间中,则在当前作用域终止之前它会一直隐藏,然后再次变为可见.
If an outer declaration of a lexically identical identifier exists in the same name space, it is hidden until the current scope terminates, after which it again becomes visible.
在 C 和 C++ 中,在多个范围内使用相同的名称是合法的.
In both C and C++ it is legal for the same name to be used within multiple scopes.
因此在您的代码中,前面的 i
将保持隐藏,直到 if
语句的范围终止.
So in your code the previous i
remains hidden till the scope of if
statement terminates.
相关文章