cpp-condicional-switch

What is and how to use the SWITCH conditional in C++

  • 5 min

The switch conditional in C++ is a control structure that allows executing different blocks of code based on the value of an expression.

If you want to learn more, check out the Introduction to Programming Course

Sometimes it is a cleaner and more readable alternative to a series of nested if-else statements. Although, many people think (myself included) that instead of improving readability, it often worsens it.

Basic Syntax

The basic syntax of a switch conditional in C++ is:

switch (expression) {
    case value1:
        // Code to execute if expression is equal to value1
        break;
    case value2:
        // Code to execute if expression is equal to value2
        break;
    // You can add more cases here
    default:
        // Code to execute if expression does not match any case
        break;
}
Copied!
  • expression: It’s the expression whose value is evaluated and compared with the case values.
  • case: Each case represents a specific value that is compared with the expression.
  • default: It’s an optional block that executes if no case matches the expression’s value.

Let’s see a basic example of using switch:

#include <iostream>

int main() {
    int number = 2;

    switch (number) {
        case 1:
            std::cout << "One" << std::endl;
            break;
        case 2:
            std::cout << "Two" << std::endl;
            break;
        case 3:
            std::cout << "Three" << std::endl;
            break;
        default:
            std::cout << "Invalid number" << std::endl;
            break;
    }

    return 0;
}
Copied!

In this example,

  • Depending on the value of numero, the program will print the corresponding number to the console.
  • If the value doesn’t match any of the defined cases, it will print Número no válido.

Fall-Through Between Cases

In C++ it is not mandatory to include a break at the end of each case (unlike other languages like C#).

If the break is omitted, the program flow will continue executing the code of the following case (this is known as “fall-through”).

#include <iostream>

int main() {
    int number = 2;

    switch (number) {
        case 1:
        case 2:
        case 3:
            std::cout << "Number between 1 and 3" << std::endl;
            break;
        default:
            std::cout << "Invalid number" << std::endl;
            break;
    }

    return 0;
}
Copied!

In this example,

  • Both cases 1, 2, and 3 will execute the same block of code and then end with the break.

Although this can be useful in some cases, it can also lead to errors if not handled carefully \

In general, don’t do it

Practical Examples

These examples have the purpose of showing how to use the Switch conditional. It does not mean it’s the best way to solve the problem they address. Normally, there are better alternatives.