C++ For Loop: Traditional Counting, Nested Loops & Range-Based Iteration

The for loop is the most widely utilized iteration construct when the number of repetitions is known before entering the loop. Modern C++ supports both the classic counter-based loop and the elegant, zero-overhead Range-Based For Loop.

1. Traditional 3-Part For Loop

#include <iostream>

int main() {
    // for (initialization; test condition; update)
    for (int i = 1; i <= 5; ++i) {
        std::cout << "Step count: " << i << "\n";
    }
    return 0;
}

2. Modern Range-Based For Loop (C++11 / C++20)

Range-based loops eliminate index out-of-bounds errors and make code exceptionally readable across arrays, vectors, and lists:

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

int main() {
    std::vector<std::string> frameworks = {"Qt", "Unreal Engine", "Boost", "CUDA"};

    // Const reference: Maximum speed, Zero copying!
    for (const auto& fw : frameworks) {
        std::cout << "Framework: " << fw << "\n";
    }

    // In-place modification using non-const reference:
    std::vector<int> scores = {10, 20, 30};
    for (auto& s : scores) {
        s *= 2; // Doubles each score directly
    }

    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why should you use 'for (const auto& x : container)' instead of 'for (auto x : container)'?

Writing 'auto x' creates a copy of every element in the container on every iteration, causing severe performance degradation for objects like std::string or large structs. Writing 'const auto& x' passes by const reference, achieving zero copying while preventing accidental modification.

Q2. Can you modify container elements during a range-based for loop?

Yes! Use a non-const reference: 'for (auto& x : container) { x *= 2; }'. This directly modifies the original elements in-place.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

C++ Arrays

Traversing 1D and 2D arrays with nested for loops.

C++ std::vector

Using range-based for loops with STL containers.

Break & Continue

Early exit and step skips inside loops.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!