Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case-Label question in C/C++

Tags:

c++

c

case

label

I came across this code

  #include<stdio.h>
  int main()
  {
      int a=1;
      switch(a)
      {   int b=20;
          case 1: printf("b is %d\n",b);
                  break;
          default:printf("b is %d\n",b);
                  break;
      }
      return 0;
  }

I expected the output to be 20 but got some garbage value. Will the output be different when this code is compiled as a .c file and .cpp file?

like image 856
user724619 Avatar asked Dec 12 '22 13:12

user724619


1 Answers

In C++ the code is ill-formed because jump to case 1 crosses initialization of b. You can't do that.

In C the code invokes UB because of the use of uninitialized variable b.

C99 [6.4.2/7] also shows a similar example.

EXAMPLE In the artificial program fragment

switch (expr)
{
   int i = 4;
   f(i);
   case 0:
     i = 17;
     /* falls through into defaultcode  */
   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 fcannot be reached.

like image 53
Prasoon Saurav Avatar answered Dec 28 '22 08:12

Prasoon Saurav