Declaring a variable as global and then as local -Shadowing-

醉酒当歌 提交于 2019-12-22 10:48:42

问题


What does it mean to declare a variable as global and then re-declare it as local like this:

int a = 0;
int main()
{
    int a = 7;
    return 0;
}

I saw this example in a reference, but I don't understand it. please put into consideration that I'm a beginner at programming with C++


回答1:


This means that in your main method if you use only a, you will refer to that one which is declared in that method, because it shadows the global one. To access the global one within main, you need to access via ::a. Within other methods if you will use a, you will refer to that one which is global for every method in that file. Scopes work like this, if it doesn't find a variable, it goes and tries to find in the outer scope and so on to the global scope.

One advice avoid from global variables




回答2:


You need to understand Scope of a variable. A variable defined within a method/curly braces is valid as long as you are referencing it within that curly braces. That said, in your code, to access the local "a", you use it directly & to use the global "a" (defined outside main()), prefix with the scope resolution operator (::a)

But, avoid a scenario like this. Give unique names.



来源:https://stackoverflow.com/questions/45784781/declaring-a-variable-as-global-and-then-as-local-shadowing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!