Please help in how the following program works(i.e behavior of if
statement inside switch default statement.) :
/**
* test.c - Test for switch construct.
*/
#include <stdio.h>
int main()
{
int i = 10 ;
printf("\n hello world\n");
switch (i) {
printf("\n In switch statement\n");
case 1:
printf("\n You entered: %d \n", i);
break;
case 2:
printf("\n You entered: %d \n", i);
break;
default :
if (9 == i) {
case 9:
printf("\n in case 9 entered value: %d\n", i);
break;
case 10:
printf("\n in case 10, entered value: %d\n", i);
break;
}
}
return 0;
}
Output:
++++++++
hello world
in case 10, entered value: 10
Not a nice program! Just a guess, but I think it jumps straight
to case 10: and ignores the if statement within the default case
since there is an matching case (10).
Also it's likely that the compiler optimises out all of the other
cases since it knows that 'i' is always 10.
You're jumping into the body of the if-statement, so bypassing the
condition.
C's switch statement is even weirder than I thought: making nonsense of the
default case, and being able to write unreachable code like this.
> Output:
> ++++++++
> hello world
>
More interesting is how you managed to produce those "+" symbols in the
output.
--
Bartc
Does the code invoke undefined behaviour?
'case' statements are basically the same as goto-labels.
The switch() basically executes a 'goto' to the matching case label.
So it 'goto'-s the 'case 10:' label and starts running from there.
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
No discussion of this topic would be complete wihout mentioning
"Duff's Device". See http://en.wikipedia.org/wiki/Duff's_device for
more details.
Paul.