LearnFrenzy
Sign in Take a free test

Control Flow, Functions and Lambdas · Lesson 7 of 33

Control Flow in Modern C++

5 min read Updated Nov 7, 2026 Saurabh Samir

C++ has the same if, switch, for, while and do-while as C – if you know C, they work identically. Modern C++ adds a few features that make loops and conditions shorter and safer: the range-based for, initialisers in if and switch, and enum class.

In this lesson

  • The range-based for loop
  • if and switch with an initialiser
  • enum class
  • The classic loops, briefly

Range-based for

#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
    std::vector<int> marks{78, 91, 64, 85};
    int total = 0;
    for (int m : marks) total += m;                 // read each element
    std::cout << "total " << total << '\n';

    for (int& m : marks) m += 5;                    // modify in place
    for (int m : marks) std::cout << m << ' ';
    std::cout << '\n';

    std::map<std::string, int> stock{{"pen", 120}, {"bag", 0}, {"book", 35}};
    for (const auto& [item, qty] : stock) {         // structured bindings: key and value
        if (qty == 0) std::cout << item << " is out of stock\n";
    }

    for (char c : std::string{"C++"}) std::cout << '[' << c << ']';
    std::cout << '\n';
    return 0;
}

Output

total 318
83 96 69 90 
bag is out of stock
[C][+][+]

Range-for works with every STL container, strings and built-in arrays. Use the classic index loop when you need the index or a different step.

if and switch with an initialiser

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> prices{{"pen", 20}, {"book", 450}};

    if (auto it = prices.find("book"); it != prices.end()) {    // it exists only in this if/else
        std::cout << "book costs " << it->second << '\n';
    } else {
        std::cout << "no book\n";
    }

    switch (int score = 87; score / 10) {                       // initialiser in a switch
        case 10: case 9: std::cout << "Grade O\n"; break;
        case 8:          std::cout << "Grade A\n"; break;
        case 7:          std::cout << "Grade B\n"; break;
        default:         std::cout << "Grade C or below\n";
    }
    return 0;
}

Output

book costs 450
Grade A

The variable declared in the initialiser is limited to that statement, so it can't leak into the rest of the function or be misused later.

enum class

#include <iostream>
#include <string>

enum class Status { Pending, Shipped, Delivered };          // scoped, strongly typed

std::string label(Status s) {
    switch (s) {
        case Status::Pending:   return "Pending";
        case Status::Shipped:   return "Shipped";
        case Status::Delivered: return "Delivered";
    }
    return "Unknown";
}

int main() {
    Status s = Status::Shipped;
    std::cout << label(s) << " (" << static_cast<int>(s) << ")\n";
    // int n = s;              // error: no implicit conversion to int
    // if (s == 1) ...         // error: can't compare with an int
    return 0;
}

Output

Shipped (1)
Plain enumenum class
Namesleak into the surrounding scope (Pending)scoped (Status::Pending)
Converts to intimplicitlyonly with static_cast
Name clashes between enumspossibleimpossible

The classic loops

#include <iostream>

int main() {
    for (int i = 1; i <= 5; i++) std::cout << i * i << ' ';     // index loop
    std::cout << '\n';

    int n = 9875, digits = 0;
    while (n > 0) { n /= 10; digits++; }                        // unknown number of steps
    std::cout << "digits: " << digits << '\n';

    for (int i = 10; i >= 0; i -= 3) {
        if (i == 4) continue;                                    // skip
        std::cout << i << ' ';
    }
    std::cout << '\n';
    return 0;
}

Output

1 4 9 16 25 
digits: 4
10 7 1 

Signed vs unsigned in loops

v.size() returns an unsigned std::size_t. Writing for (int i = 0; i < v.size(); i++) triggers a sign-compare warning, and v.size() - 1 on an empty vector wraps around to a huge number. Prefer range-for, or use std::size_t i, or std::ssize(v) (C++20) for a signed size.

Practice

Try it yourself

  1. Use a range-for with structured bindings to print every student who scored at least 80 from a std::map<std::string, int>.

    Show solution
    #include <iostream>
    #include <map>
    #include <string>
    
    int main() {
        std::map<std::string, int> scores{{"Asha", 91}, {"Ravi", 74}, {"Meera", 85}};
        for (const auto& [name, score] : scores) {
            if (score >= 80) std::cout << name << ' ' << score << '\n';
        }
        return 0;
    }

    Output

    Asha 91
    Meera 85

Quick check

How do you modify elements in a range-for?

Use a reference: for (int& x : v).

Where is a variable declared in if (auto x = f(); x > 0) visible?

Only inside that if statement and its else.

Why prefer enum class?

Scoped names and no implicit conversion to int – fewer clashes and mistakes.

Summary

  • Range-for (with & or const&) is the default loop over containers; structured bindings unpack pairs.
  • if/switch initialisers keep helper variables tightly scoped.
  • Prefer enum class; watch signed/unsigned comparisons with size().

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links