Using a variable with the same name in different spaces

前端 未结 4 717
走了就别回头了
走了就别回头了 2020-12-20 10:51

This code compiles, but I have a run time error in Visual Studio:

Run-time check failure #3 - the variable \'x\' is being used without being initializ

相关标签:
4条回答
  • 2020-12-20 11:26

    please use SRO( Scope resolution operator ::) to tell compiler which x is real x in your mind. As user defined names are mangled( Names are decorated) something like this to avoid ambiguity at it's level, these are just names used by compiler that best suits it

    int x = 15;// Real name = gui_x
    int main()
    {
        int x = x;// lui_x
        return 0;
    }
    

    In this way run-time will know which version you are using but to avoid ambiguity it expects from you to use specific names. Sometimes above problem arise where you don't know that you are using already used names. For this C++ has created SRO.
    Now in case of array x is address & not integer that stores something, that's why compiler didn't jumbled. You need to write

    namespace abc //now all global variables are belongs to this ns abc
    int x = 15;// Real name = gui_x
    int main()
    {
    int x = abc::x;// lui_x
    return 0;
    }
    
    0 讨论(0)
  • 2020-12-20 11:27

    x is defined at the left of =.

    so in x[x], [x] refer to the global one,

    whereas in x = x;, x hides the global x and initializes from itself -> UB.

    0 讨论(0)
  • 2020-12-20 11:35

    There is no scope resolution operator in C, so you may not be able to use

    int x = x;
    

    in your program.

    0 讨论(0)
  • 2020-12-20 11:42

    When you declare a new variable, its name becomes visible right here

    int x =
    //     ^- there
    

    because it is at that point the variable is fully declared, and as such; its name means something. At this point in time any other (previously declared variable) in a surrounding scope will be hidden.

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