Reputation: 53
I was working around with the Switch statement when I accidentally wrote the following piece of code(on gcc in C)
int a = 2;
switch(a)
{
default:
printf("Default\n");
case 1:
printf("One\n");
case2 :
printf("Two\n");
}
The output I got was:
Default
One
Two
I am able to understand how this output came about, however I don't understand why this does not throw up an error, I mean I clearly don't have a case label (in case2) right? Also I have observed the same result if I right "case2" as "casex" for example. Whereas if I don't put in any case label it gives a compile time error.
Any help would be appreciated, thanks!
Upvotes: 2
Views: 1645
Reputation: 180316
I am able to understand how this output came about, however I don't understand why this does not throw up an error, I mean I clearly don't have a case label (in case2) right?
Yes, case2 :
is not a case label, but it is a valid valid ordinary label. Any statement may be preceded by such a label. Since you're using GCC, you could consider turning on the -Wall
option (or specifically -Wunused-label
), in which case GCC should warn that that label is unused (because it is not the target of any goto
statement).
Also I have observed the same result if I right "case2" as "casex" for example.
Well, sure. casex :
is also a valid ordinary label.
Whereas if I don't put in any case label it gives a compile time error.
I suppose you must mean that you leave the colon, but remove the whole label text (case2
/ casex
). That would indeed yield invalid code. If you removed the whole line, however, then of course that would be fine.
Upvotes: 4
Reputation: 32596
you missed the break
so the execution continue after each case (but with a != 1 to have these 3 outputs)
note case2:
is considered as a label (for a goto) so is not an error
Upvotes: 2
Reputation: 12817
What happens here is you got to the default label, and because you had no break, you followed through to all other cases.
Upvotes: -1