C switch case Statement

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:

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


C switch case flowchart


Example of C Switch Statement

The following example demonstrates C switch case statement :

In this tutorial, you have learned how to use C switch case statement to control flow of complex conditionals in the program.

  • Was this tutorial helpful ?
  • YesNo