Back to C++
2026-03-055 min read

C++ Switch

Learn C++ Switch step by step with clear examples and exercises.

Why This Matters

Welcome to this detailed guide on the C++ switch statement! This tutorial is designed to help you understand its practical uses, common mistakes, and how it can enhance your problem-solving skills in programming.

Why This Matters

The switch statement is a powerful tool in C++ that allows for efficient execution of code based on different cases. It's particularly useful when you have multiple conditions to check, as it can make your code cleaner and easier to read compared to using multiple if-else statements. Understanding the switch statement will prepare you for various programming challenges, real-world coding scenarios, and even job interviews!

Prerequisites

Before diving into the switch statement, it's essential that you have a solid understanding of the following concepts:

  1. C++ basics: variables, data types, operators, functions, and control structures (if, else, for, etc.)
  2. Understanding the difference between value-based and reference-based comparison
  3. Familiarity with compilers and standard library functions

Core Concept

Syntax

The basic syntax of a switch statement in C++ is as follows:

switch (expression) {
case constant1:
// code to be executed if expression matches constant1
break;
case constant2:
// code to be executed if expression matches constant2
break;
...
default:
// code to be executed if no matching case is found
}

The expression is evaluated once at the beginning of the switch block, and then compared with each case label. If a match is found, the corresponding code block is executed until the break statement is encountered or the end of the switch block is reached. If no matching case is found, the code in the default case (if present) will be executed.

Value-based vs. Reference-based Comparison

Note that that C++ performs value-based comparison by default when comparing int and char types within a switch statement. This means that if you have multiple cases with the same value but different data types, only the first matching case will be executed. For example:

int main() {
int num = 5;
switch (num) {
case 5:
cout << "Case 5";
break;
case '5':
cout << "Case '5'"; // This will not be executed
break;
}
}

In this example, the output will only be "Case 5", because the switch statement performs value-based comparison and finds a match in the first case with the integer value of 5.

To perform reference-based comparison (comparing addresses instead of values), you can use the const_cast function:

int main() {
int num = 5;
char ch = '5';
switch (const_cast<void*>(&num)) {
case const_cast<void*>(&ch):
cout << "Case '5'"; // This will be executed now
break;
...
}
}

Range-based Switch

C++17 introduced a new feature called the range-based switch, which allows you to iterate over an array or container and match against its elements directly:

#include <array>
#include <iostream>

int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
switch (arr) {
case {1, 2, 3}:
std::cout << "First three elements";
break;
...
}
}

In this example, the switch statement checks if the array's elements match the specified sequence. If a match is found, the corresponding code block is executed.

Worked Example

Let's consider a simple example of using the switch statement to implement a basic calculator:

#include <iostream>

int main() {
char operation;
int num1, num2;

std::cout << "Enter an operator (+, -, *, /): ";
std::cin >> operation;

std::cout << "Enter two operands: ";
std::cin >> num1 >> num2;

switch (operation) {
case '+':
std::cout << num1 + num2;
break;
case '-':
std::cout << num1 - num2;
break;
case '*':
std::cout << num1 * num2;
break;
case '/':
if (num2 == 0) {
std::cout << "Error: Division by zero";
} else {
std::cout << num1 / num2;
}
break;
default:
std::cout << "Invalid operator";
}

return 0;
}

In this example, the user is prompted to enter an operator and two operands. The switch statement then checks the entered operator and performs the corresponding calculation. If an invalid operator is entered, the program outputs "Invalid operator."

Common Mistakes

  1. Forgetting to include the break statement: This can cause the code in subsequent cases to be executed unintentionally.
  2. Comparing different data types within a single case: Remember that C++ performs value-based comparison by default, so if you have multiple cases with the same value but different data types, only the first matching case will be executed.
  3. Not handling the default case: If no matching case is found, the code in the default case (if present) will be executed, which may or may not be what you intended.
  4. Misunderstanding range-based switch: The range-based switch only checks for exact matches of the container's elements. To check for a subset of elements, use a combination of case labels and logical operators (e.g., case {1, 2, 3}: or case {1, 2}:).

Practice Questions

  1. Write a program that takes an integer as input and outputs its corresponding day of the week using a switch statement (assuming Sunday is 0 and Saturday is 6).
  2. Implement a simple menu system using a switch statement, where the user can choose between different options like "Calculate area", "Calculate perimeter", or "Quit".
  3. Write a program that takes two integers as input and outputs their greatest common divisor (GCD) using Euclid's algorithm and a switch statement to handle edge cases.

FAQ

  1. Why does the switch statement perform value-based comparison by default?
  • Value-based comparison is more efficient for smaller data types like int and char, as it involves simple bitwise operations. However, for larger data types or custom classes, reference-based comparison may be necessary to ensure proper functioning of the switch statement.
  1. Can I use a switch statement with floating-point numbers?
  • Yes, you can use a switch statement with floating-point numbers, but remember that it will still perform value-based comparison by default. To compare floating-point numbers more accurately, consider using a tolerance or converting them to integers before comparing.
  1. What happens if I forget the break statement in a switch case?
  • If you forget the break statement in a switch case, the code execution will continue with the next case until another break is encountered or the end of the switch block is reached. This can lead to unintended consequences and bugs in your program.
  1. Can I use a loop within a switch statement?
  • No, it's not possible to use a loop directly within a switch statement. However, you can create a loop outside the switch block and use it to iterate through multiple cases or control the flow of your program based on the results of the switch statement.
C++ Switch | C++ | XQA Learn