Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 364
Johan Bezem Avatar asked Jan 06 '12 11:01

Johan Bezem


1 Answers

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.

like image 125
rodrigo Avatar answered Nov 11 '22 12:11

rodrigo