Found this code at C Puzzles.
#include
int main()
{
int a=1;
switch(a)
{ int b=20;
case 1: printf(\"b is %d\\n\",b);
You're using a variable with an indeterminate value (invoking undefined behaviour) by jumping past the initialization of the variable b
. The program can produce any value and it will be correct.
The C standard even covers this case (in a non-normative example).
ISO/IEC 9899:2011 §6.8.4.2 The
switch
statement:7 EXAMPLE In the artificial program fragment
switch (expr) { int i = 4; f(i); case 0: i = 17; /* falls through into default code */ 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 functionf
cannot be reached.
Note the 'indeterminate value' comment.
There is some room for discussion about whether accessing an indeterminate value leads to undefined behaviour. Under some circumstances (trap representations), it can lead to undefined behaviour. It will take me some time to determine whether 'possibly undefined behaviour' should be considered 'undefined behaviour'. Accessing an uninitialized variable is a bad idea, and there is nothing you can say about the value that is printed in your code.
#include<stdio.h>
int main()
{
int a = 1;
switch(a) {
int b=20;
printf("This gets called!\n");
case 1:
printf("b is %d\n",b);
break;
default:
printf("b is %d\n",b);
break;
}
return 0;
}
The key here is that int b=20;
never gets called. The compiler will create the variable b
but it never gets initialised.
b
is not being initialized. Put it outside of the switch statement.
Inside switch statement
nothing will be accepted like assigning values to the variable
and printing except inside case
. if you want the b value assign it outside the switch . Also b value should be like garbage value it can't change until assign some values to the particular location.