Code:
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;
}
Output:
It prints some garbage value for b
when does the declaration of b takes place here
Why b is not initialized with 20 here???
Because memory will be allocated for
int bbut when the application is run “b = 20” will never be evaluated.This is because your
switch-statement will jump down to eithercase 1:1 ordefault:, skipping the statement in question – thusbwill be uninitialized and undefined behavior is invoked.The following two questions (with their accepted answers) will be of even further aid in your quest searching for answers:
How can a variable be used when it’s definition is bypassed? 2
Why can’t variables be declared in a switch statement?
Turning your compiler warnings/errors to a higher level will hopefully provide you with this information when trying to compile your source.
Below is what
gccsays about the matter;1 since
int awill always be 1 (one) it will always jump here.2 most relevant out of the two links, answered by me.