Scope of Loop Variables

What is the scope of variables declared within the initialization statement of a for loop?

In C++, variables declared within the initialization statement of a for loop have a scope limited to the loop body. The variables are only accessible within the loop and are destroyed at the end of each iteration. Example:

#include <iostream>

int main() {
  for (int i = 0; i < 5; ++i) {
    // i is accessible within the loop body
    std::cout << i << "\n";
  }
  // i is not accessible outside the loop
  std::cout << i << "\n"; 
}
error: 'i': undeclared identifier

In this example, the variable i is declared within the initialization statement of the for loop. It is accessible only within the loop body and cannot be used outside the loop.

If you need to access the loop variable after the loop ends, you can declare it before the loop and use it within the loop initialization statement:

#include <iostream>

int main() {
  int i;
  for (i = 0; i < 5; ++i) {
    // i is accessible within the loop body
    std::cout << i << "\n";
  }
  // i is accessible here
  std::cout << "Final value of i: " << i << "\n";
}
0
1
2
3
4
Final value of i: 5

By declaring the variable i outside the loop, you can control its scope and access it after the loop if needed.

The scope rules for variables declared in the initialization statement of a for loop apply to all versions of C++, ensuring consistent behavior across different standards.

Conditionals and Loops

Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Using break in Nested Loops
How can I break out of nested loops using the break keyword?
Conditional Operator Precedence
What is the precedence of the conditional (ternary) operator compared to other operators?
Condition in a do-while Loop
Is it possible to have a condition that always evaluates to false in a do-while loop?
Short-Circuit Evaluation Order
In what order are the conditions evaluated in short-circuit evaluation?
Detecting Infinite Loops
How can I detect and prevent infinite loops in my C++ code?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant