Using a variable with the same name in different spaces

柔情痞子 提交于 2019-11-29 13:06:57

x is defined at the left of =.

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

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

Bo Persson

When you declare a new variable, its name becomes visible right here

int x =
//     ^- there

because it is at that point the variable is fully declared, and as such; its name means something. At this point in time any other (previously declared variable) in a surrounding scope will be hidden.

There is no scope resolution operator in C, so you may not be able to use

int x = x;

in your program.

please use SRO( Scope resolution operator ::) to tell compiler which x is real x in your mind. As user defined names are mangled( Names are decorated) something like this to avoid ambiguity at it's level, these are just names used by compiler that best suits it

int x = 15;// Real name = gui_x
int main()
{
    int x = x;// lui_x
    return 0;
}

In this way run-time will know which version you are using but to avoid ambiguity it expects from you to use specific names. Sometimes above problem arise where you don't know that you are using already used names. For this C++ has created SRO.
Now in case of array x is address & not integer that stores something, that's why compiler didn't jumbled. You need to write

namespace abc //now all global variables are belongs to this ns abc
int x = 15;// Real name = gui_x
int main()
{
int x = abc::x;// lui_x
return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!