C++:C++ For Loops and Range-Based For Loops (C++11)
C++•Loops

C++ For Loops and Range-Based For Loops (C++11)

Learn index-based counting loops, container iteration, and const-reference iteration to avoid object copying.

Syntax

for (int i = 0; i < n; ++i) {} for (const auto& item : container) {}

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
range-based forLoop ConstructIterates over elements in any container providing begin() and end().

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

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

int main() {
    // 1. Traditional counter loop
    std::cout << "--- Counter Loop ---" << "\n";
    for (int i = 1; i <= 3; ++i) {
        std::cout << "Iteration #" << i << "\n";
    }

    // 2. Modern Range-based for loop with const reference
    std::cout << "\n--- Container Iteration ---" << "\n";
    std::vector<std::string> engines = {"GCC", "Clang", "MSVC"};
    for (const auto& engine : engines) {
        std::cout << "-> Compiler Engine: " << engine << "\n";
    }

    return 0;
}
Expected Output:
--- Counter Loop ---
Iteration #1
Iteration #2
Iteration #3

--- Container Iteration ---
-> Compiler Engine: GCC
-> Compiler Engine: Clang
-> Compiler Engine: MSVC

How It Works: Step-by-Step

  • Lines 7-10: Executes traditional counter loop with ++i increment.
  • Lines 15-18: Uses const auto& to iterate without copying vector elements.

Key Concepts

  • Range-based for loops (C++11) eliminate index boundary errors.
  • Using const auto& item avoids deep copies of strings and vector elements.
  • Prefer prefix ++i over postfix i++ for non-primitive iterator loops.

Common Mistake: Iterating with for (auto item : vector) instead of for (const auto& item : vector)

Omitting the reference & creates a full copy of every single item in the container.

❌ Incorrect
for (auto s : largeStringVector) { /* Copies each string! */ }
✅ Correct
for (const auto& s : largeStringVector) { /* Zero-copy read-only access */ }

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler