switch and the ? : Operator

switch

When you compare one variable against many exact values, switch is neat and readable. It works with whole numbers and chars:

#include <iostream>
using namespace std;

int main() {
    int day;
    cin >> day;
    switch (day) {
        case 1:
            cout << "Monday\n";
            break;
        case 2:
            cout << "Tuesday\n";
            break;
        case 3:
            cout << "Wednesday\n";
            break;
        default:
            cout << "Some other day\n";
    }
    return 0;
}

Input (what the user types)

2

Output

Tuesday
  • Each case is one possible value.
  • break jumps out of the switch.
  • default runs when no case matches (like else).

Common mistake: Forgetting break. Without it, C++ keeps going into the next case too! This is called fall-through:

#include <iostream>
using namespace std;

int main() {
    int level = 1;
    switch (level) {
        case 1:
            cout << "One\n";       // no break here...
        case 2:
            cout << "Two\n";       // ...so this runs as well
            break;
    }
    return 0;
}

Output

One
Two

The ternary operator ? :

For a quick choice between two values, use condition ? valueIfTrue : valueIfFalse:

#include <iostream>
#include <string>
using namespace std;

int main() {
    int age = 15;
    string type = (age >= 18) ? "adult" : "child";
    cout << "Ticket type: " << type << "\n";

    int a = 8, b = 13;
    int bigger = (a > b) ? a : b;
    cout << "Bigger: " << bigger << "\n";
    return 0;
}

Output

Ticket type: child
Bigger: 13

Remember: Use the ternary only for short, simple choices. For anything bigger, a normal if/else is easier to read.

HOME LABS COMMUNITY DASHBOARD