Search⌘ K

Switch Statement

Explore how to use the switch statement in C++ for handling exact value conditions efficiently. Understand the syntax, use of break statements, case merging for identical outcomes, and limitations with data types. This lesson helps you write clearer conditional code for specific cases.

When installing software, you might come across a statement telling you that this installation is taking some amount of memory. You are then asked if you want to continue with the installation process and told to enter y or Y to continue or x or X to quit. This scenario can be implemented using an if-else block as shown below:

if(ans == ‘Y’ || ans == ‘y’)
// continue the installation
else if(ans == ‘X’ || ans == ‘x’)
// terminate the installation
else
// invalid input terminate
Installing software condition

Similar to this scenario, whenever you are checking for an exact value and not a range, you can also use the switch-case statement.

The switch-case construct

This tests an input variable for equality with any number of cases and then executes the corresponding code. The workflow that works in this case is as follows:

The switch statement evaluates a variable. The value of the variable is compared to each case label within the switch block. If a match is ...