C Language

Switch Statement

In C Language by Baqir AliLeave a Comment

The switch statement is a multi way conditional statement generalizing the if-else statement. The switch statement evaluates the value of an expression and branches to one of the case labels.

  • Duplicate labels are not allowed, so only one case will be selected.
  • The expression must evaluate an integer, character or enumeration.

General Form

 switch (expression) 
 {
   case constant1:   statement1;
   case constant2:   statement2;
   ...
   case constantn:   statementn;
   default:   default_statement;
 } 
  • The case labels can be in any order and must be constants.
  • Notice the body of the switch statement is a compound statement.

The effect of a switch

  1. Evaluate a switch expression.
  2. Go to the case label having a constant value that matches the value of the expression found in step 1. If a match is not found, go to the default label; if there is no default label, terminate the switch.
  3. Terminate the switch when a break is encountered, or by “falling off the end”.

Default Statement

The default label can be put anywhere in the switch.

  • When C sees a switch statement, it evaluates the expression and then looks for a matching case label.
  • If none is found, the default label is used.
  • There may be at most one default label in a switch.
  • Typically, it occurs last although it can occur anywhere.

Break Statement

Typically, the last statement before the next case or default label is a break statement and break statement inside a switch means that execution will continue after the switch statement.

  • If a break statement is not there, execution “falls through” to the next statement.

The break statement interrupts the normal flow of control.

Leave a Comment