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?
is correct.
So in your program, the global
i
is ignored when the locali
is encountered and it is initialized to itself. You'll get a garbage value as a result.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