Summary: in this tutorial, you will learn how to use C switch case statement to execute a block of code based on the selection from multiple choices.
Introduction to C switch case statement
The C switch case statement is a control flow statement that tests whether a variable or expression matches one of a number of constant integer values, and branches accordingly.
The switch case
statement is used to control very complex conditional and branching operations. For controlling simple conditional and branching operations, you can use if else statement.
The following illustrates the C switch case statement syntax:
1 2 3 4 5 6 7 8 9 | switch (expression) { case value1: /* execute unit of code 1 */ break; case value2: /* execute unit of code 2 */ break; ... default: /* execute default action */ break; } |
Let’s examine the C switch statement syntax in more detail:
- In the C switch case statement, the selection is determined by the value of an expression that you specify, which is enclosed in the parentheses after the keyword switch. The data type of the value that is the result of the expression must be an integer, otherwise, the compiler will issue an error message.
- The case constant expression must be a constant integer.
- When a break statement is executed, it causes an immediate exit from the switch. The break statement is not mandatory, but if you don’t put a break statement at the end of the case block, the statements for the next case in the sequence will execute.
- The default statement is the default choice of the switch case statement if the expression does not match any cases. The break statement after the default statement is not necessary unless you put another case statement below it.
The following flowchart illustrates the C switch case statement
Example of C Switch Statement
The following example demonstrates C switch case statement :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /* * File: main.c * Author: zentut.com * Purpose: Demonstrates c switch statement */ #include <stdio.h> int main() { int color = 1; printf("Please choose a color(1: red,2: green,3: blue):\n"); scanf("%d", &color); switch (color) { case 1: printf("you chose red color\n"); break; case 2: printf("you chose green color\n"); break; case 3: printf("you chose blue color\n"); break; default: printf("you did not choose any color\n"); } return 0; } |
1 2 3 | Please choose a color(1: red,2: green,3: blue): 2 you chose green color |
In this tutorial, you have learned how to use C switch case statement to control flow of complex conditionals in the program.