Explain output of this C program

后端 未结 4 2032
我寻月下人不归
我寻月下人不归 2021-01-27 09:08

Found this code at C Puzzles.

#include

int main()
{
  int a=1;
  switch(a)
  {   int b=20;
      case 1: printf(\"b is %d\\n\",b);
                       


        
4条回答
  •  深忆病人
    2021-01-27 09:31

    You're using a variable with an indeterminate value (invoking undefined behaviour) by jumping past the initialization of the variable b. The program can produce any value and it will be correct.

    The C standard even covers this case (in a non-normative example).

    ISO/IEC 9899:2011 §6.8.4.2 The switch statement:

    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.

    Note the 'indeterminate value' comment.


    There is some room for discussion about whether accessing an indeterminate value leads to undefined behaviour. Under some circumstances (trap representations), it can lead to undefined behaviour. It will take me some time to determine whether 'possibly undefined behaviour' should be considered 'undefined behaviour'. Accessing an uninitialized variable is a bad idea, and there is nothing you can say about the value that is printed in your code.

提交回复
热议问题