Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

c++ - Using a variable with the same name in different spaces

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 initialized...

int x = 15;
int main()
{
    int x = x;
    return 0;
}

I don't understand that behavior... in the error box when I click continue the program resumes and x has a corrupted content (like -8556328 instead of 15).

Why does this code work without a problem, and the int array is well declared?

const int x = 5;
int main()
{
     int x[x] = {1,2,3,4};
     return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...