Normally when using a switch
statement, you cannot define and initialize variables local to the compound statement, like
switch (a)
{
int b = 5; /* Initialization is skipped, no matter what a is */
case 1:
/* Do something */
break;
default:
/* Do something */
break;
}
However, since the switch
statement is a statement like for
or while
, there is no rule against not using a compound statement, look here for examples. But this would mean, that a label may be used between the closing parenthesis after the switch
keyword and the opening brace.
So in my opinion, it would be possible and allowed to use a switch
statement like this:
switch (a)
default:
{
int b = 5; /* Is the initialization skipped when a != 1? */
/* Do something for the default case using 'b' */
break;
case 1: // if a == 1, then the initialization of b is skipped.
/* Do something */
break;
}
My question: Is the initialization necessarily performed in this case (a != 1)? From what I know of the standards, yes, it should be, but I cannot find it directly in any of the documents I have available. Can anyone provide a conclusive answer?
And before I get comments to that effect, yes, I know this is not a way to program in the real world. But, as always, I'm interested in the boundaries of the language specification. I'd never tolerate such a style in my programming team!
Most people think of a switch
as a mutiple if, but it is technically a calculated goto
. And the case <cte>:
and default:
are actually labels. So the rules of goto
apply in these cases.
Your both your examples are syntactically legal, but in the second one, when a==1
the b
initialization will be skipped and its value will be undefined. No problem as long as you don't use it.
REFERENCE:
According to C99 standard, 6.2.4.5, regarding automatic variables:
If an initialization is specified for the object, it is performed each time the declaration is reached in the execution of the block;
So the variable is initialized each time the execution flow reaches the initialization, just as it were an assignment. And if you jump over the initialization the first time, then the variable is left uninitialized.
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