在范围内重新定义变量

2022-01-23 00:00:00 compiler-errors g++ c++

为什么以下代码在 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.

相关文章