Back: Casts
Forward: Namespaces
 
FastBack: Namespaces
Up: Changeable C++
FastForward: Compiler Quirks
Top: Autoconf, Automake, and Libtool
Contents: Table of Contents
Index: Index
About: About this document

16.2.4 Variable Scoping in For Loops

C++ has always permitted the declaration of a control variable in the initializer section of for loops:

 
for (int i = 0; i < 100; i++)
{
  ...
}

The original language specification allowed the control variable to remain live until the end of the scope of the loop itself:

 
for (int i = 0; i < j; i++)
{
  if (some condition)
    break;
}

if (i < j)
  // loop terminated early

In a later specification of the language, the control variable's scope only exists within the body of the for loop. The simple resolution to this incompatible change is to not use the older style. If a control variable needs to be used outside of the loop body, then the variable should be defined before the loop:

 
int i;

for (i = 0; i < j; i++)
{
  if (some condition)
    break;
}

if (i < j)
  // loop terminated early


This document was generated by Gary V. Vaughan on May, 24 2001 using texi2html