Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is declaring a variable in switch statement allowed? but not declaration + initialization? [duplicate]

  1. 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?
  2. 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.

  1. 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?

like image 584
topcat Avatar asked Mar 20 '26 08:03

topcat


1 Answers

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.

like image 147
P.W Avatar answered Mar 21 '26 21:03

P.W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!