C++ global and local variables

前端 未结 8 871
遇见更好的自我
遇见更好的自我 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:52

    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.

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

    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

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