Explain output of this C program

后端 未结 4 2031
我寻月下人不归
我寻月下人不归 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.

    0 讨论(0)
  • 2021-01-27 09:31
    #include<stdio.h>
    int main()
    {
        int a = 1;
        switch(a) {   
            int b=20;
            printf("This gets called!\n");
            case 1: 
                    printf("b is %d\n",b);
                    break;
            default:
                    printf("b is %d\n",b);
                    break;
        }
        return 0;
    }
    

    The key here is that int b=20; never gets called. The compiler will create the variable b but it never gets initialised.

    0 讨论(0)
  • 2021-01-27 09:49

    b is not being initialized. Put it outside of the switch statement.

    0 讨论(0)
  • 2021-01-27 09:52

    Inside switch statement nothing will be accepted like assigning values to the variable and printing except inside case. if you want the b value assign it outside the switch . Also b value should be like garbage value it can't change until assign some values to the particular location.

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