Language: EN

cpp-condicional-switch

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

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

Sometimes it is a cleaner and more readable alternative to a series of nested if-else statements. Although many people believe (myself included), 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;
}
  • expression: This is the expression whose value is evaluated and compared with the values of the cases.
  • case: Each case represents a specific value that is compared with the expression.
  • default: This is an optional block that executes if no case matches the value of the expression.

Let’s look at 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;
}

In this example,

  • Depending on the value of number, the program will print the corresponding number to the console.
  • If the value does not match any of the defined cases, it will print Invalid number.

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;
}

In this example,

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

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

In general, do not do it

Practical Examples

:::::::

These examples are intended to show how to use the Switch conditional. It does not mean that it is the best way to solve the problems they address. Usually, there are better alternatives.