C++C++
BeginnerLesson 3 of 18

Conditions: if, switch and Operators – C++

Making decisions with if/else, switch, logical operators and the ternary operator.

With if, you run code only when a condition is true. The condition goes in parentheses, the block in curly braces.

#include <iostream>

int main() {
    int punkte = 73;
    if (punkte >= 90) {
        std::cout << "very good\n";
    } else if (punkte >= 70) {
        std::cout << "good\n";
    } else {
        std::cout << "needs improvement\n";
    }
}

Comparisons: ==, !=, <, >, <=, >=. You combine them with && (and), || (or) and ! (not). The ternary operator ? : is an expression that yields a value.

int x = 15;
bool ok = x > 10 && x % 2 != 0;
std::cout << std::boolalpha << ok << '\n';                       // true
std::cout << (x >= 18 ? "adult" : "minor") << '\n'; // minor

switch suits many fixed cases, especially with enum class. Do not forget the break, otherwise execution "falls through" into the next case. Since C++17, if may contain an initialization – the variable lives only within the if/else block:

enum class Tag { Mo, Di, Sa };
Tag t = Tag::Sa;
switch (t) {
    case Tag::Mo:
    case Tag::Di: std::cout << "Weekday\n"; break;
    case Tag::Sa: std::cout << "Weekend\n"; break;
}

std::string text = "Hello";
if (auto pos = text.find('l'); pos != std::string::npos) {
    std::cout << "l at position " << pos << '\n';   // 2
}
WarningClassic typo: if (x = 5) is an assignment, not a comparison – and always true. -Wall warns about it. Numbers count as true when they are not 0.