How are statements that come before any case labelled statement in a switch-case block treated.
Please explain the behavior of the following programs
prog1:
#include<stdio.h>
int main()
{
switch(1)
{
int i=0;
case 1:printf("%d",i);
}
getchar();
return 0;
}
Output: garbage value.
prog2:
#include<stdio.h>
int main()
{
switch(1)
{
printf("Inside Switch");
case 1:printf("Case 1\n");
}
printf("Outside Switch");
getchar();
return 0;
}
Output:
Case 1
Outside Switch.
The statements before a case labelled statement seem unreachable according to program 2 but then why don’t i get an error for an undeclared variable i in the first program (only a warning).
Would be really helpful if someone could explain in detail that how the switch statement is treated internally.
This is best explained by quotations from the c standard.
I am quoting the relevant parts from the standard which apply to your question here.
6.8.4.2 The switch statement
Para 4:
Para 2:
FootNote:
Para 7:
EXAMPLE In the artificial program fragment
The above mentioned applies to both of the code examples in the Question.
Example 1,ihas an Indeterminate value since it was never initialized & hence prints garbage, While inExample 2,printfcall is not reached because the control jumps to the matchingcaselabel.