Using a variable with the same name in different spaces

前端 未结 4 725
走了就别回头了
走了就别回头了 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;
    }
    

提交回复
热议问题