Friday, July 12, 2013

Switch Statement in C

The switch statement is multi-decision statement which matches an expression to a set of constant values and branches to the corresponding value.

The switch case statement is placed in place of if...else if we have more number of matches to a variable.

The syntax of the switch-case statement is as shown below.

Syntax:

  • switch(expression)
  • {
  • case 1: Set of statements
  • case 2: Set of statements
  • .
  • .
  • .
  • default:Set of Statements
  • }
Consider the following example to understand the switch-case clearly.

Example:
  • switch(x)
  • {
  • case 1: printf("Hello it is 1");break;
  • case 2: printf("Hello it is 2");break;
  • default :printf("It is not 1 or 2");
  • }
You might be wondering why we have used break at the end of each case and why we have not used at the default.

A break is used to terminate the current flow of execution. Here if we have not used a break, then once the switch statement enters a case, it executes all the statements of all the cases under that case. If we use break, once the case is executed, the control comes out of switch. For the default case, even if we use, as this is the last part, there is no problem even if we don't use break.

To know more about a break statement, click here.

Note: We have to use only integer values, to evaluate in the switch case.

However, the switch case also takes the char values as the cases, to know why this happens, click here.