How switch Statement Work?
The working of the switch statement in C is as follows:
- Step 1: The switch variable is evaluated.
- Step 2: The evaluated value is matched against all the present cases.
- Step 3A: If the matching case value is found, the associated code is executed.
- Step 3B: If the matching code is not found, then the default case is executed if present.
- Step 4A: If the break keyword is present in the case, then program control breaks out of the switch statement.
- Step 4B: If the break keyword is not present, then all the cases after the matching case are executed.
- Step 5: Statements after the switch statement are executed.
We can also understand the working of the switch statement in C using the flowchart.
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases).
- Switch case statements follow a selection-control mechanism and allow a value to change control of execution.
- They are a substitute for long if statements that compare a variable to several integral values.
- The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
In C, the switch case statement is used for executing one condition from multiple conditions. It is similar to an if-else-if ladder.
The switch statement consists of conditional-based cases and a default case.