Can anyone explain the output of this program in C?

Possible duplicate:
Why can't variables be declared in a switch statement? How can a variable be used when its definition bypasses?

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

works on gcc 4.6.3, the output is not 20. What is happening here?

+6
source share
5 answers

Initializing variables inside switch statements is bad practice and undefined behavior.

+8
source

The switch statement has the following structure:

 switch ( expression ){ // declarations case constant-expression : ... case constant-expression : ... default : ... } 

The declarations section is used at compile time to declare variables, but it is not used at run time to initialize them (in fact, no instructions are executed in this section). Not the difference between declaring and initializing a variable. Since b never initialized, your code has the same result as:

 int main(){ int b; printf("b is %d\n", b); return 0; } 

This is clearly undefined. Compiling with the -Wall flag will catch that you are using an uninitialized value.

+6
source

If you enable compiler warnings, you will see:

 warning: 'b' may be used uninitialized in this function 

This is not a valid place to initialize b , and therefore it contains uninitialized data during printing instead of 20. You invoke undefined behavior.

+5
source

The switch makes goto in the corresponding case based on the value of the switch variable and nothing more. Right now you are bypassing b initialization, so it will print everything that was in memory at that time in that place.

0
source

The var scope property. If you move

 int b=20; 

Outside the switch block, it will work.

-2
source

Source: https://habr.com/ru/post/918468/


All Articles