Folks,
Recently started learning C.
Stuck at a point. Its about working of switch-case statement.
Here’s the code :
#include<stdio.h>
int main() {
int i=4;
switch(i) {
default :
printf("%s","Default");
case 0:
printf("%s","Case 0");
case 1:
printf("%s","Case 1");
case 2:
printf("%s","Case 2");
return 0;
}
}
I personally think, “Default” should be printed, as it doesn’t match with any of case value.
But when I run the code in Turbo C, what I observed was this :
Default
Case 0
Case 1
Case 2
Even same was observed here : http://www.ideone.com/pFh1d
What is the problem ? It is the compiler problem or any mistake in my code ?
EDIT :
PS : What wrong does it make if at all I have to write default case first. Any harm ?
But once the compiler knows that it has to execute the default statement, why we need to put a break statement after the statements of default case ?
The switch statement will jump to the appropriate
caseordefaultand then the code will continue until the nextbreakstatement.As your code has no
breakit will start off at thedefault:and simply continue through all the following statements. This can sometimes be a useful trick when programming similar conditions, but generally the lack of break statements will cause confusion.Also the final
returnis in the wrong place it should be after the switch statement.Amend as follows.