Question-Label in C / C ++

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 will get some garbage cost. Will the result be different if this code is compiled as a .c file and a .cpp file?

+4
source share
5 answers

Either this is a programming puzzle, or a disgusting mistake.

switch acts as a computed goto . That way it will either goto 1; , or goto default; . In any case, he jumps past b = 20; and prints the uninitialized garbage value!

The C ++ compiler should improve the situation a bit by abandoning compilation.

+4
source

In C ++, the code is poorly formed because switching to case 1 intersects the initialization b . You cannot do this.

In C, the code calls UB due to the use of the uninitialized variable b .

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

EXAMPLE In a fragment of an art program

 switch (expr) { int i = 4; f(i); case 0: i = 17; /* falls through into defaultcode */ default: printf("%d\n", i); } 

an object whose identifier exists exists with the duration of automatic storage (inside the block), but is never initialized, and therefore, if the control expression has a nonzero value, the call to the printf function will have access to an undefined value. Similarly, a function call f not possible.

+8
source

the thread of execution never reaches int b=20; , so you get the uninitialized value of b (it is still allocated on the stack due to how compilers allocate the stack stack).

for the destination to be achieved, it must be in the case statement or outside and above the switch (I am surprised that the compiler did not spit out warnings about inaccessible code ...).

+1
source

No, the int b = 20 statement is not actually executed, since you will skip it.

I will expect your compiler to warn about this.

0
source

If you use the Linux gcc compiler, compile it with the -Wall option to verify this. Everything inside the case block, except for the “case case”, is never performed perfectly. But how it works in C / C ++, your answer largely depends on the type of compiler you use. The nut again, as I said above, int b=20 should never be reached, and therefore the result of the garbage value when printing it. A.

One more thing in such situations is good if you also tell us the type and version of your compiler in order to get more accurate answers.

0
source

All Articles