C++ global and local variables

前端 未结 8 870
遇见更好的自我
遇见更好的自我 2021-01-16 03:26

I have encountered the following code:

#include
using namespace std;
int i = 1;
int main(int argc,char ** argv)
{
    int i = i;
    cout&l         


        
相关标签:
8条回答
  • 2021-01-16 03:36

    The concept most answers are describing is called shadowing.

    0 讨论(0)
  • 2021-01-16 03:41

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

    0 讨论(0)
  • 2021-01-16 03:42

    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.

    0 讨论(0)
  • 2021-01-16 03:44
    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.

    0 讨论(0)
  • 2021-01-16 03:48

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

    0 讨论(0)
  • 2021-01-16 03:49

    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.

    0 讨论(0)
提交回复
热议问题