在不同的空格中使用具有相同名称的变量 [英] Using a variable with the same name in different spaces

查看:94
本文介绍了在不同的空格中使用具有相同名称的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码已编译,但我在 Visual Studio 中遇到运行时错误:

This code compiles, but I have a run time error in Visual Studio:

运行时检查失败#3 - 正在使用变量'x'而不进行初始化...

Run-time check failure #3 - the variable 'x' is being used without being initialized...



int x = 15;
int main()
{
    int x = x;
    return 0;
}



我不明白这种行为...在错误框中单击继续程序恢复,x具有损坏的内容(如 -8556328 而不是 15 )。

为什么这段代码没有问题,int数组是否已经被声明?

Why does this code work without a problem, and the int array is well declared?

const int x = 5;
int main()
{
     int x[x] = {1,2,3,4};
     return 0;
}


推荐答案

=

的左侧定义了 x [x] [x] 指全局变量,

so in x[x], [x] refer to the global one,

x = x; x 隐藏全局 x 并从其自身初始化 - > UB。

whereas in x = x;, x hides the global x and initializes from itself -> UB.

这篇关于在不同的空格中使用具有相同名称的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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