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:27

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 ::

查看更多
\"骚年 ilove
3楼-- · 2019-02-20 13:28

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.

查看更多
三岁会撩人
4楼-- · 2019-02-20 13:28

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.

查看更多
甜甜的少女心
5楼-- · 2019-02-20 13:35

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.

查看更多
干净又极端
6楼-- · 2019-02-20 13:39

The concept most answers are describing is called shadowing.

查看更多
Rolldiameter
7楼-- · 2019-02-20 13:42

Variables in the innermost scope will override variables with the same Name without warning.

查看更多
登录 后发表回答