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 som开发者_StackOverflow中文版e 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
f
cannot be reached.
Either that's a programming puzzle or a heinous bug.
switch
acts like a computed goto
. So it will either goto 1;
or goto default;
. In either case, it jumps past b = 20;
and prints an uninitialized, garbage value!
A C++ compiler should improve the situation somewhat by refusing to compile this.
the flow of execution never reaches int b=20;
, so your getting the uninitialized value of b (it still get allocated on the stack due to how compilers allocate stack vars).
for the assignment to be reached it must be in a case statement or outside and above the switch (I'm surprised the compiler didn't spit out warnings about unreachable code...).
No, the int b = 20
statement isn't actually executed, as you skip over it.
I would expect your compiler to warn about this though.
If you are using a "gcc" Linux compiler, compile it with -Wall
option to check for that. Anything inside a case block, except the "case statements" are never executed ideally. But how it works in C/C++, your answer depends a lot on the type of compiler you are using. Nut again as i told above, int b=20
should never be reached, and thus the result of the garbage value when you print it.
One more thing, in such situations it is good if you also let us know the type and version of compiler you are using, to get more accurate answers.
精彩评论