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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With