C++ Switch

In C++, the switch statement allows programs to execute one of multiple possible code blocks based on a given value. It simplifies decision-making when dealing with fixed options, such as menu selections, categories, or predefined choices.

Tutorials dojo strip



How the switch Statement Works

The expression inside switch() is evaluated once, and then its value is compared against different case labels.

  • If a case matches, its block of code runs.
  • If no match is found, the default case executes (if provided).
  • The break keyword prevents further execution beyond the matched case.

Syntax

C++




Example: Identifying Motorcycle Categories

C++

If bikeType is 2, the output will be “Cruiser”.




The break Keyword

The break statement ensures that execution stops once a case is matched.
Without break, all subsequent cases would execute, causing unwanted behavior.

Example (Without break)

C++

Even if bikeType is 1, all cases would execute, displaying “Sport bikeCruiserTouring bike”.




The default Keyword

The default case ensures that the program handles unexpected values by providing an alternative output.

Example

C++

Since carType is 5, and there is no matching case, the output will be “Unknown vehicle type”.

Tutorials dojo strip