Conditionals and Loops

Scope of Loop Variables

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

Abstract art representing computer programming

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved