重新定义范围内的变量 [英] redefinition of variable inside scope

查看:141
本文介绍了重新定义范围内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码在g ++下编译时没有任何警告或错误?
我看到的问题是,在第一行定义的变量x可以在if范围内访问,但尽管它被重新定义了。

  int main(){
int x = 5;
std :: cout<< X;
if(true){
int x = 6;
std :: cout<< X;



$ div $解析方案

C -


6.2.1在C99中:



如果声明标识符的声明符或类型说明符出现在块内或函数定义中的参数声明列表中,则该标识符具有块范围,该范围终止于关闭关联的}块

...


如果一个词汇相同的标识符的外部声明存在于同一个名字空间中,直到当前作用域终止,然后再次变为可见为止,它是隐藏的。

在C和C ++中,在多个作用域内使用相同的名称是合法的。

所以在你的代码中,前面的保持隐藏状态,直到的范围,如果语句终止。

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;
    }
}

解决方案

According to C-

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.

In both C and C++ it is legal for the same name to be used within multiple scopes.

So in your code the previous i remains hidden till the scope of if statement terminates.

这篇关于重新定义范围内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆