Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 359
Aminos Avatar asked Oct 01 '15 20:10

Aminos


People also ask

Can you use spaces in variable names?

Variable names cannot contain spaces. A # character in the first position of a variable name defines a scratch variable.

Can you have two variables with the same name?

Said in simple terms, if multiple variables in a program have the same name, then there are fixed guidelines that the compiler follows as to which variable to pick for the execution.

Can you use spaces in R?

A basic rule of R is to avoid naming data-frame columns using names that contain spaces. R will accept a name containing spaces, but the spaces then make it impossible to reference the object in a function.


Video Answer


3 Answers

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.

like image 184
Jarod42 Avatar answered Oct 16 '22 22:10

Jarod42


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.

like image 42
Bo Persson Avatar answered Oct 16 '22 21:10

Bo Persson


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

int x = x;

in your program.

like image 5
Adi Avatar answered Oct 16 '22 22:10

Adi