Control Flow I: if, switch, ternary

সিদ্ধান্ত গ্রহণ — if, else, switch

Read: ~25 min 12 practice problems

1. The if Statement

if.cpp
#include <iostream>
int main() {
    int n = 42;
    if (n > 0)       std::cout << "positive\n";
    else if (n < 0) std::cout << "negative\n";
    else             std::cout << "zero\n";
}
Classic bug if (x = 5) assigns 5 to x and tests truthiness — it's not a comparison! Use ==. Compile with -Wall to catch this.

2. C++17 if-init

Initialize a variable scoped to the if-block:

ifinit.cpp
#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> m = {{"a", 1}, {"b", 2}};
    if (auto it = m.find("a"); it != m.end()) {
        std::cout << "Found: " << it->second << "\n";
    }
    // it is not visible here — clean!
}

3. switch — When You Have Many Cases

switch.cpp
#include <iostream>

int main() {
    int day = 3;
    switch (day) {
        case 1: std::cout << "Sun\n"; break;
        case 2: std::cout << "Mon\n"; break;
        case 3: std::cout << "Tue\n"; break;
        case 4: std::cout << "Wed\n"; break;
        default: std::cout << "unknown\n";
    }
}
Fall-through Missing break falls through to next case. Use [[fallthrough]]; (C++17) when intentional.

4. The Ternary Operator

ternary.cpp
#include <iostream>
int main() {
    int a = 7, b = 3;
    int max_val = (a > b) ? a : b;
    std::cout << "Max = " << max_val << "\n";
}
When to use ternary For simple value selection only. Multi-line logic = use full if. Nested ternaries hurt readability.

5. Boolean Idioms

BadGood
if (flag == true)if (flag)
if (flag == false)if (!flag)
if (count != 0)if (count) (or be explicit)
return x > 0 ? true : false;return x > 0;

6. Practice Problems

  1. Write a program that classifies a number as positive, negative, or zero.
    ✨ Show Answer

    See the example in section 1 above — same idea.

  2. FizzBuzz: print 1..15. For multiples of 3 print "Fizz", multiples of 5 print "Buzz", multiples of both print "FizzBuzz".
    ✨ Show Answer
    fizzbuzz.cpp
    #include <iostream>
    int main() {
        for (int i = 1; i <= 15; ++i) {
            if      (i % 15 == 0) std::cout << "FizzBuzz\n";
            else if (i %  3 == 0) std::cout << "Fizz\n";
            else if (i %  5 == 0) std::cout << "Buzz\n";
            else                 std::cout << i << "\n";
        }
    }
  3. Why must case values in switch be compile-time constants?
    ✨ Show Answer

    The compiler often builds a jump table for fast dispatch. Constants are required so it can compute the table at compile time.

  4. What's the bug in: if (a = 0) {...}?
    ✨ Show Answer

    Assignment, not comparison. a becomes 0, the if is always false. Use ==.

  5. Use the ternary to print "even" or "odd" for n=7.
    ✨ Show Answer
    std::cout << (n % 2 == 0 ? "even" : "odd") << "\n";
  6. Write a switch that prints the season for month numbers 1-12.
    ✨ Show Answer
    switch (m) {
        case 12: case 1: case 2: std::cout << "winter\n"; break;
        case  3: case 4: case 5: std::cout << "spring\n"; break;
        case  6: case 7: case 8: std::cout << "summer\n"; break;
        case  9: case10: case11: std::cout << "autumn\n"; break;
        default: std::cout << "invalid\n";
    }

    Multiple case labels can fall into the same block intentionally.

  7. Refactor: return x > 5 ? true : false;
    ✨ Show Answer

    return x > 5; — the comparison already produces a bool.

  8. Write code that checks if a year is a leap year.
    ✨ Show Answer
    bool isLeap(int y) {
        return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
    }
  9. When is switch better than chained if-else?
    ✨ Show Answer

    When testing one variable against many integer/enum constants. Compilers can generate jump tables, making it O(1) instead of O(n).

  10. What does [[fallthrough]]; do?
    ✨ Show Answer

    An attribute (C++17) telling the compiler "I intentionally want fall-through here, don't warn me". Place it as the last statement of a case before falling into the next.

  11. Use if-init to safely call a function that returns -1 on error.
    ✨ Show Answer
    if (int result = compute(); result != -1) {
        use(result);
    }
  12. Rewrite without ternary: int sign = (x > 0) ? 1 : (x < 0 ? -1 : 0);
    ✨ Show Answer
    int sign;
    if (x > 0)      sign =  1;
    else if (x < 0) sign = -1;
    else             sign =  0;

Summary

Branches: if/else, switch, ternary ?:. Use switch for many integer cases. if (init; cond) in C++17 scopes setup variables tightly. Always compile with -Wall to catch = vs == bugs.

Next Module → Control Flow II: Loops & Range-based for.