---
id: cpp-for-loop-foreach
title: "C++ The foreach Loop"
category: "Programming_Language"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["range-based for loop", "for-each", "C++ foreach 루프"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-07-04
updated_at: 2026-07-04
review_reason: ""
merge_history: []
tags: ["cpp", "programming-language", "w3schools", "loops", "foreach", "range-based-for"]
raw_sources: ["https://www.w3schools.com/cpp/cpp_for_loop_foreach.asp"]
applied_in: []
github_commit: ""
---

# [[CPP The foreach Loop]]

## 🎯 한 줄 통찰 (One-line insight)
This is a genuinely NEW construct that C never had at all — the range-based `for (type var : collection)` loop, introduced only in C++11 (2011), eliminates BOTH the manual index variable AND the manual bounds-check entirely, meaning C++ programmers get a loop style C users had no equivalent for, and the exact same syntax works interchangeably on an array of numbers or the characters of a string. [S1]

## 🧠 핵심 개념 (Core concepts)
- **`for (type variableName : collectionName) { ... }`** — the range-based ("for-each") loop; iterates every element without an index variable or manual size tracking. [S1]
- **Works on arrays** — `for (int num : myNumbers)` visits each element directly. [S1]
- **Works on strings too** — `for (char c : word)` visits each character. [S1]
- **C++11 introduction** — this loop form did not exist before the 2011 standard. [S1]
- **No index or bounds-checking needed** — unlike a traditional `for` loop with `i < length`, the range-based form has no risk of an off-by-one error since it handles iteration internally. [S1]

## 📖 세부 내용 (Details)
- Looping through an array: `int myNumbers[5] = {10, 20, 30, 40, 50}; for (int num : myNumbers) { cout << num << "\n"; }`. [S1]
- Looping through a string's characters: `string word = "Hello"; for (char c : word) { cout << c << "\n"; }`. [S1]

## ⚖️ 모순 및 업데이트 (Contradictions & updates)
- **C에는 없던 C++ 고유 반복문**: 인덱스 변수나 수동 경계 확인 없이 배열/문자열의 모든 원소를 순회하는 range-based for 루프는 C++11(2011)에 새로 도입된 개념으로, C 튜토리얼에는 대응 챕터가 전혀 없었다는 점이 확인됨. [S1]

## 🛠️ 적용 사례 (Applied in summary)
현재 발견된 실제 적용 사례가 없습니다 — 배열과 문자열 모두에 동일한 for-each 문법을 적용할 수 있다는 점이 실전 코드 순회 작업의 간결함을 보여준다. [S1]

## 💻 코드 패턴 (Code patterns)
The range-based for loop working identically on an array and a string (C++11+):
```cpp
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int num : myNumbers) {
  cout << num << "\n";
}

string word = "Hello";
for (char c : word) {
  cout << c << "\n";
}
```

## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)

## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[C++ Tutorial]]
- **관련 개념:** [[CPP For Loop]], [[CPP For Loop Nested]], [[CPP Arrays]]
- **참조 맥락:** foreach 루프 — 중첩 for 루프(For Loop Nested) 챕터로 이어짐, 배열(Arrays) 섹션과 직접 연결.

## 📚 출처 (Sources)
- [S1] W3Schools — C++ The foreach Loop — https://www.w3schools.com/cpp/cpp_for_loop_foreach.asp

## 📝 변경 이력 (Change history)
- 2026-07-04: Initial draft synthesized from the W3Schools "C++ The foreach Loop" page (Astra wiki-curation, P-Reinforce v3.1 format).
