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.
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?
The case label functions as a target of a goto statement.
The C++ standard states in [stmt.dcl]/3:
It is possible to transfer into a block, but not in a way that bypasses declarations with initialization.
So the below will fail:
case 'a':
int x = 4; //will fail
whereas the following will not fail:
case 'a':
int x; // this is ok
x = 4;
In response to the OP's edit:
In this particular case, just the declaration makes x visible throughout the switch statement as there are no braces {} surrounding it.
So x can be used in with the other cases as well although the compiler will warn about using it uninitialized. Note that reading of an uninitialized variable is undefined behavior.
To answer the last part of your question:
Suppose the declaration with initialization was allowed it would mean that that particular value of x (4 in this case) would have to be used in other cases as well.
Then it would seem as if code for multiple cases was executed. So this is not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With