Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Behavior of if construct in switch case defualt construct.

1 view
Skip to first unread message

Mukesh

unread,
Mar 26, 2010, 6:54:52 AM3/26/10
to
Hello,

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

paul

unread,
Mar 26, 2010, 7:04:53 AM3/26/10
to
> Please help in how the following program works(i.e behavior of if
> statement inside switch default statement.) :

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.

bartc

unread,
Mar 26, 2010, 7:11:58 AM3/26/10
to
Mukesh wrote:

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

paul

unread,
Mar 26, 2010, 7:17:21 AM3/26/10
to
>> Output:
>> ++++++++
>> hello world
>>
>
>
> More interesting is how you managed to produce those "+" symbols in the
> output.

Does the code invoke undefined behaviour?

Mukesh

unread,
Mar 26, 2010, 7:25:28 AM3/26/10
to
it's added by me ... + symbols not comes with output :)
>
> --
> Bartc

Willem

unread,
Mar 26, 2010, 7:28:06 AM3/26/10
to
Mukesh wrote:
) Please help in how the following program works(i.e behavior of if
) statement inside switch default statement.) :

'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

Paul N

unread,
Mar 26, 2010, 8:38:18 AM3/26/10
to

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.

0 new messages