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.
Answers to questions are automatically generated and may not have been reviewed.
Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break