简体   繁体   中英

C++ global and local variables

I have encountered the following code:

#include<iostream>
using namespace std;
int i = 1;
int main(int argc,char ** argv)
{
    int i = i;
    cout<<i<<endl; // which i?
    return 0;
}

It can pass the compile, but gives the wrong answer, how to explain this?

The int i = i; statement in main() declares a local variable that hides the global variable.

It initializes itself with itself (which has an indeterminate value). So the global i simply isn't used.

the Local variable is accessible, analogous to calling two people with a same name, one inside the room, and one outside the room. The one who is in the scope you are trying to access it , hears it.

最内部作用域中的变量将覆盖具有相同名称的变量,而不会发出警告。

Variables in deeper scopes will override the variables with the same name in a higher scope. To access a global variable, precede the name with ::

int main()
{
    int i=i;
    return 0;
}

is correct.

So in your program, the global i is ignored when the local i is encountered and it is initialized to itself. You'll get a garbage value as a result.

When you have two variable with same name, one is global and other is local. Then in this case local variable will get in use only in that particular scope. And global variable is unused.

Now, coming to your problem

#include<iostream>
using namespace std;
int i = 1;//Global Variable decleration
int main(int argc,char ** argv)
{
    int i = i; // Local to main
    cout<<i<<endl; // which i?
    return 0;
}

int i = i; compiles without any error but when you run the program it will produce error because local i has indeterminate value.

In C++, it is possible to access the global variable if you have a local variable with the same name but you have to use the scope resolution operator ::

change the line:

int i = i;

to

int i = ::i;

and the program will compile and work

大多数答案所描述的概念称为阴影

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM