+1-617-874-1011 (US)

  +44-117-230-1145 (UK)

The switch statement

The Switch Statement allows you to select from multiple choices based on a set of fixed values for a given expression. Here are the common Switch Statement syntax:

switch (expression)
{
case value1: /* execute unit of code 1 */
break;
case value2: /* execute unit of code 2 */
break;
...
default: /* execute default action */
break;
}

In the Switch Statement, the selection is determined by the value of an expression that you specify, which is enclosed between the Parentheses after the keyword Switch.

The Data Type of value which is returned by expression must be an integer value otherwise the statement will not compile. The case constant expression must be an integer value and all values in case statement are equal.

When a Break Statement is executed, it causes execution to continue with the statement following the closing brace for the switch. The Break Statement is not mandatory, but if you don't put a Break Statement at the end of the statements for a case, the statements for the next case in sequence will be executed as well, through to whenever another break is found or the end of the switch block is reached. This can lead some unexpected program logics happen.

The Default Statement is the default choice of the switch statement if all cases statement are not satisfy with the expression. The Break after the default statements is not necessary unless you put another case statement below it.

Some important points of Switch - Case:

  • values for 'case' must be integer or character constants
  • the order of the 'case' statements is unimportant
  • the default clause may occur first (convention places it last)
  • you cannot use expressions or ranges
The switch statement Help Homework Help

switch statement Example:

#include <stdio.h>
#include <conio.h>
int main()
{
int number;
printf(“Enter number: ”);
scanf(“%d”,&number);
switch(number)
{
/* none when 0*/
case 0 :
printf("None\n");
break;
/* Single when 1 */
case 1 :
printf("Single\n");
break;
/* Double when 2 */
case 2 :
printf("Double\n");
break;


/* For case 3, 4, 5 then statement will be executed till break is reached i.e. till the output of several.
*/

case 3 :
case 4 :
case 5 :
printf("Several\n");
break;
default :
printf("Many\n");
break;
}
}

Topics in C Programming