- Why is declaring + initializing a variable inside a case of a switch statement not allowed & gives an error, but if it is declared it on one line then assigned a value on another, it compiles?
- Why the variable that was declared in a previous case can be used(operated on) in another matching case even if the previous case statements did not execute!
This code compiles with no errors or warnings:
char ch; cin>> ch;
switch(ch)
{
case 'a':
int x; // How come this is ok but not this(int x = 4;)?
x = 4;
cout<< x << endl;
break;
case 'b':
x += 1; // x is in scope but its declaration did not execute!
cout<< x << endl;
break;
case 'c':
x += 1;
cout<< x << endl;
break;
}
I expected case 'b'
Or case 'c'
to not know that there is a variable called x. I know the variable is still in scope in case b and case c.
case 'a' prints 4
case 'b' prints 1
case 'c' prints 1
Edit: No the other question thread that is marked as a possible duplicate does not answer my question.
- why is the variable x can not be defined and initialized? what problems would that create that it is not allowed to do so?
If it is allowed to define the variable only in one statement, then the variable gets used in the matching case and whatever garbage was in there gets used; so what difference does it make from declare + initializing the value?