Are local variables in the compound switch statement initialized when the label `default:` is placed outside the curly braces?

Usually, when using the switch you cannot define and initialize local variables for a compound statement, for example

 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 is an expression of type for or while , there is no rule against using the compound statement here for examples . But that would mean that the label could be used between the closing bracket after the switch keyword and the opening bracket.

So, in my opinion, it would be possible and allowed to use the switch as follows:

 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: is initialization necessary in this case (a! = 1)? From what I know about standards, yes, it should be, but I can’t find it directly in any of the documents available to me. Can anyone give a definitive answer?

And before I get comments on this question, yes, I know that this is not a way of programming in the real world. But, as always, I'm interested in the boundaries of the language specification. I would never tolerate such a style in my development team!

+6
source share
1 answer

Most people think of switch as a mutiple if, but it's technically calculated by goto . Both case <cte>: and default: are actually labels. Therefore, in this case, goto rules apply.

Both of your examples are syntactically legal, but in the second case, when a==1 initialization of b will be skipped and its value will be undefined. No problem if you do not use it.

REFERENCE :

According to standard C99, 6.2.4.5, regarding automatic variables:

If an object is set to initialize, it is executed each time the declaration is executed when the block is executed;

Thus, the variable is initialized each time the thread reaches the initialization, as well as the destination. And if you go through initialization for the first time, then the variable will remain uninitialized.

+7
source

Source: https://habr.com/ru/post/905300/


All Articles