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:
| Parameter | Type | Description |
|---|---|---|
| range-based for | Loop Construct | Iterates over elements in any container providing begin() and end(). |
Ready-to-Run Code Example
Executable in CompilraRun 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
C++ While and Do-While Loops with Examples
Learn pre-test while loops and post-test do-while loops in C++.
C++ Break and Continue Loop Control Statements
Alter standard loop iteration using break and continue in C++.
C++ std::vector (Dynamic Arrays): Methods and Memory
Master std::vector for dynamic contiguous arrays with push_back, emplace_back, and indexing.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.