The body of switch
statement in C language is one single continuous compound statement with several entry points. Each case/default
label is an entry point. You can enter that compound statement at any entry point, and it will continue to execute all the way to the end (unless another jump statement intervenes, of course). In other words, case
labels in switch
work the same way goto
labels do. The default
label is not in any way different from case
labels in this respect.
This is exactly what you observe in your experiment. The statement in your switch
looks as follows
{
printf("%s","Default");
printf("%s","Case 0");
printf("%s","Case 1");
printf("%s","Case 2");
return 0;
}
You enter this statement through your default:
label at the very beginning. Since you do not alter the control flow after entering the body of your switch
(aside from probably misplaced final return
), all four printf
s get a change to "fire".
The meaning of your question that begins with "But once the compiler knows that it has to execute the default statement..." is not clear to me. The functionality of switch/case
construct in C is as I described above. That's what the "compiler knows". You, on the other hand, seem to follow some completely unfounded self-invented misconceptions about what switch/case
does and for some reason expect the compiler to follow the same misconceptions. I'd say that you need to read a book on C language basics instead of trying to guess what various language elements do.
There's nothing wrong with making the default
case first. Considering what I said above, in some situations the ordering of the labels inside the statement matters. When it matters, you have to arrange them in accordance with your intent. If you need your default
case to be the first, make it first. If you don't need it (or it makes no difference) you can put it last or wherever else you want to put it.