Using a switch statement allows you to test multiple conditions and only execute a specific block if the condition is true. Although it works similarly to an if…else if….else statement, the syntax is simpler and easier to read and manage.
This tutorial focuses on showing you how to create and work with switch statements in C programming.
The switch statement is easy to implement. The general syntax is as shown below:
How It Works
The switch statement implements a simple logic to evaluate each of the case blocks.
It starts by evaluating the expression inside the switch block. Then, it compares the value from the switch block against each case block.
Once it locates a match inside one of the defined case blocks, it executes the code inside that block until it encounters the break keyword.
If it does not encounter a match in either of the defined case blocks, it jumps to the default statement and executes the code inside it. The default block is optional and omittable if there is no required action for a non-matching scenario
NOTE: It is good to ensure each case statement terminates with a break statement to prevent all the statements after the matching block from executing.
C Switch Case Statement Example
Let us illustrate the switch statement with a very simple example:
If we run the above example, we should get an output similar to the one below:
The following flow diagram illustrates the logic of the above program:
A Nested Switch Statement
C allows you to have nested switch statements inside a switch statement. The nested switch statement ties to the value of the outer switch.
Consider the following example:
In the example above, we implement two switch statements. The first checks if the dept provided is 1. If true, it proceeds to the next switch block and checks for the valid access code.
If the dept value is not one, the execution moves to the default block.
The following is the execution of the code above with correct and incorrect dept and access code.
In the first example, both the dept and access code are correct; thus, the execution never reaches the default blocks.
In the second example, both the dept and access code are incorrect; hence, the execution immediately jumps to the first default block.
Guidelines for Switch Statements
The following are quick guidelines worth noting when creating switch statements in C.
- You must pass an expression to the switch keyword.
- Case statements must check for unique values
- Terminate each case block using the break keyword.
- You can nest multiple switch statements.
- You can include a default statement when an action is necessary for non-matching cases.
This guide has walked you through the basics of creating and using C switch statements. Switch statements are useful when you have complex decision cases that might be difficult to implement with the and if else statement.