Variable definition inside switch statement

According to the C standard (6.8 Statements and blocks), emphasis mine:

3 A block allows a set of declarations and statements to be grouped
into one syntactic unit. The initializers of objects that have
automatic storage duration, and the variable length array declarators
of ordinary identifiers with block scope, are evaluated and the values
are stored in the objects
(including storing an indeterminate value
in objects without an initializer) each time the declaration is
reached in the order of execution, as if it were a statement,
and
within each declaration in the order that declarators appear.

And (6.8.4.2 The switch statement)

4 A switch statement causes control to jump to, into, or past the
statement that is the switch body, depending on the value of a
controlling expression, and on the presence of a default label and the
values of any case labels on or in the switch body. A case or default
label is accessible only within the closest enclosing switch
statement.

Thus the initializer of variable i is never evaluated because the declaration

  switch (val) {         
      int i = 1;   //i is defined here
      //...

is not reached in the order of execution due to jumps to case labels and like any variable with the automatic storage duration has indeterminate value.

See also this normative example from 6.8.4.2/7:

EXAMPLE In the artificial program fragment

switch (expr) 
{ 
    int i = 4;
    f(i); 

case 0: 
    i = 17; /* falls through into default code */ 
default:
    printf("%d\n", i); 
}

the object whose identifier is i exists with
automatic storage duration (within the block) but is never
initialized, and thus if the controlling expression has a nonzero
value, the call to the printf function will access an indeterminate
value. Similarly, the call to the function f cannot be reached.

Leave a Comment