redefinition of variable inside scope(重新定义作用域内的变量)
问题描述
为什么以下代码在 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.
这篇关于重新定义作用域内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:重新定义作用域内的变量


基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01