Specifying a case in switch-case
is to set label
This label
is used by the compiler to jump to label
corresponding to val
.
The problem with the above code starts with {}
bundling all the codes in the switch statement into one scope.
When a block is started, space is allocated to memory for local variables
In the above code, if val
is not 1
, the part that initializes newVal
will not be executed, resulting in an error.
This is because there is only one {}
in the switch statement
If you specify a scope for each case, you can declare a variable inside the switch door
switch (val)
{
case 1:
{
int newVal = 42;
break;
}
case 2:
break;
}
}
© 2024 OneMinuteCode. All rights reserved.