Variable declared and initialized in switch statement

Why does this program not output 20?

#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; } 
+4
source share
9 answers

Since the switch statement jumps to the appropriate case, so the line int b = 20 will never be executed.

+30
source

Your compiler should warn you about this. The initialization of "b" is at the beginning of the switch statement, where it will never be executed - execution will always come directly from the header of the switch statement to the corresponding case label.

+8
source

It does not output "b = 20" because b is set inside the switch statement, and this instruction is never executed. What you want is:

 int b = 20; switch (a) { case 1: { printf("b is %d\n", b); break; } default: { printf("b is %d\n", b); break; } } 
+2
source

Gcc warns that b is not initialized when printf () is called

you need to move "int b = 20" before the switch ()

+2
source

Inside the switch is a hidden goto . So basically what happens is really

 int a=1; if(a==1){ //case 1 goto case1; }else{ //default goto default; } int b=20; case1:.... 
+2
source

Remember that case labels in a switch are called β€œlabels” for some reason: they are pretty ordinary labels, just like the ones you can goto to. Actually, this works for a switch : it's just a structured version of goto that just jumps from switch to the appropriate label and continues execution from there. In your code, you always go on to initialize b . So b never initialized.

+2
source

The code

 int b = 20 

actually does two things:

 int b 

and

 b = 20 

The compiler sets the variable b when it compiles the program. This is an automatic variable that goes onto the stack. But he does not assign meaning to it until the execution of the program reaches this point.

Up to this point, it is not known what value the variable has.

This does not apply to a global variable or a static variable - they are initialized when the program starts.

+2
source

Compiling with gcc (using cygwin on Windows) displays a warning message -

warning: unreachable code at the beginning of the switch statement

and the output is undefined or garbage, which clearly says that part of the initialization would never be executed and therefore the value is undefined.

Note: You can ask the question that if the code or line is not available, then why do not we get the error: 'b' is not declared.

The compiler checks the syntax of the program (above the check if b is declared) and finds it correct (b is declared), although this is semantically / logically incorrect.

Probably in the future, compilers may become even smarter and be able to detect such errors.

+1
source

Line

int b=20;

Not executed until key is entered. You will need to move it over the switch statement to get 20 output.

0
source

All Articles