C – Switch Statement 2017-08-05T19:55:37+00:00

Switch Statement :

  • Switch statement simulate the use of multiple if statement.The switch statement is probably the single most syntactically awkward and error-prone feature of the C language. Syntax of c switch statement is


    case constant1:

    statements 1;


    case constant2:

    statements 2;



    statements n;



When the switch statement is executed, the expression in the switch statement is evaluated and the control is transferred directly to the group of statements whose case label value matches the value of the expression. Each group of statement ends with a break statement. The execution of break statement causes immediate exit from the switch statement. If break statement is not present, then the execution will falls trough all the statement in the selected case.  If none of the case-label value matches the value of expression, then none of the group within the switch statement will be selected and the control is transferred directly to the statement that follows the switch statement c.

The expression that forms the argument of switch is evaluated to either char or integer. Similarly the constant expression follows the keyword case should be a value int or char. That is, names of variable can also be used. Switch can test for only equality.

Take a look at the following if-else code, and notice how confusing it can be to have nested if tests, even just a few levels deep:


Output :

Enter a number


Given number is greater than 5

It’s illegal to have more than one case label using the same value. For example, the following block of code won’t compile because it uses two cases with the same.

int temp = 100;



case 10 : printf(“10”);


case 10 : printf(“10”); // won’t compile!


case 100 :printf(“1000”);


default : printf(“default”);



Break and Fall-Through in switch Blocks:

When case constants are evaluated from the top to down, and the first case constant that matches the switch’s expression is the execution entry point. In other words, once a case constant is matched, C will execute the associated code block, and all subsequent code blocks .

Example :

Output :

Enter a number between 1 and 5



Given number is 3

Given number is 4

Given number is 5

Prev Next