C++ global and local variables

2019-02-20 13:06发布

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?

8条回答
混吃等死
2楼-- · 2019-02-20 13:48
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.

查看更多
▲ chillily
3楼-- · 2019-02-20 13:51

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

查看更多
登录 后发表回答