C - Tricky Switch Case working .. !

sgokhales picture sgokhales · Apr 25, 2011 · Viewed 7.9k times · Source

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 ?

Answer

Richard Harrison picture Richard Harrison · Apr 25, 2011

The switch statement will jump to the appropriate case or default and then the code will continue until the next break statement.

As your code has no break it will start off at the default: 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 return is in the wrong place it should be after the switch statement.

Amend as follows.

        int i=4;
        switch(i) {

                default :       
                        printf("%s","Default");
                        break;
                case 0:         
                        printf("%s","Case 0");
                        break;
                case 1:         
                        printf("%s","Case 1");
                        break;
                case 2:         
                        printf("%s","Case 2");
                        break;

        }
        return 0;