Search⌘ K

Switch Statement

Explore how to use the switch statement in C++ to manage decisions based on a single variable's value. This lesson explains its syntax, compares it with else-if statements, and demonstrates the importance of break and default cases through practical examples.

Introduction

Suppose your teacher is writing remarks on your report card based on your grade.

We can use the else-if statement here, but choice is extensive. Here, the switch statement comes in. Whenever we have to check the value of a single variable against an extensive number of choices, it is better to use the switch statement.


The switch statement evaluates the given expression and then compares its value with each case label. If the value of a case label equals the value of the expression, the statement(s) specific to that case is executed.


Syntax #

The basic syntax of the switch statement is given below:

📝 Switch expression and case label accept variables of int or char data ...