Variable definition inside switch statement

前端 未结 5 1998
青春惊慌失措
青春惊慌失措 2020-11-28 15:37

In the following code, why is the variable i not assigned the value 1?

#include       

int main(void)
{   
    int          


        
相关标签:
5条回答
  • 2020-11-28 16:11

    The initialization of variables with automatic storage durations is detailed in C11 6.2.4p6:

    1. For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. (Entering an enclosed block or calling a function suspends, but does not end, execution of the current block.) If the block is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate. If an initialization is specified for the object, it is performed each time the declaration or compound literal is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached.

    I.e. the lifetime of i in

    switch(a) {
        int i = 2;
        case 1: printf("%d",i);
                break;
        default: printf("Hello\n");
    }
    

    is from { to }. Its value is indeterminate, unless the declaration int i = 2; is reached in the execution of the block. Since the declaration is before any case label, the declaration cannot be ever reached, since the switch jumps to the corresponding case label - and over the initialization.

    Therefore i remains uninitialized. And since it does, and since it has its address never taken, the use of the uninitialized value to undefined behaviour C11 6.3.2.1p2:

    1. [...] If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

    (Notice that the standard itself here words the contents in the clarifying parenthesis incorrectly - it is declared with an initializer but the initializer is not executed).

    0 讨论(0)
  • 2020-11-28 16:26

    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.

    0 讨论(0)
  • 2020-11-28 16:30

    Line for initialization of i variable int i = 1; is never called because it does not belong to any of available cases.

    0 讨论(0)
  • 2020-11-28 16:31

    In the case when val is not zero, the execution jumps directly to the label default. This means that the variable i, while defined in the block, isn't initialized and its value is indeterminate.

    6.8.2.4 The switch statement

    1. 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.
    0 讨论(0)
  • 2020-11-28 16:36

    Indeed, your i is declared inside the switch block, so it only exists inside the switch. However, its initialization is never reached, so it stays uninitialized when val is not 0.

    It is a bit like the following code:

    {
       int i;
       if (val==0) goto zerovalued;
       else goto nonzerovalued;
       i=1; // statement never reached
       zerovalued:
         i = 10;  
         printf("value:%d\n",i);
         goto next;
      nonzerovalued:
         printf("value:%d\n",i);
         goto next;
      next:
         return 0;
     }
    

    Intuitively, think of raw declaration like asking the compiler for some location (on the call frame in your call stack, or in a register, or whatever), and think of initialization as an assignment statement. Both are separate steps, and you could look at an initializing declaration in C like int i=1; as syntactic sugar for the raw declaration int i; followed by the initializing assignment i=1;.

    (actually, things are slightly more complex e.g. with int i= i!=i; and even more complex in C++)

    0 讨论(0)
提交回复
热议问题