[comp.lang.c++] Scope of variables declared in 'for' statement

nevin1@ihlpf.ATT.COM (00704a-Liber) (06/11/88)

We were thinking about the declaration of variables within 'for' statements.
This kind of this puzzled us:

void forSample()
{
	int sum = 0;
	sum += 100;
	for (int i = 1; i < 10; i++)
		sum += i;
	sum += 200;
}

The scope of "i" is from the place it is declared to the end of the
smallest block enclosing the for statement.  While this is consistent
with the way that declarations work elsewhere, there is another consistent
way this could be defined that we would find more useful.  Instead the
scope of "i" could be inside the for statement only; in other words a
block containing the declaration and the for statement would be
implicitly created.  Here is some 'translator output' that demonstrates
what we mean:

as current C++ does it:			as we wish it did:

void forSample()			void forSample()
{					{
	int sum = 0;				int sum = 0;
	sum += 100;				sum += 100;
	{					{
		int i;					int i;
		for (i=1; i<10; i++)			for (i=1; i<10; i++)
			sum += i;				sum += i;
		sum += 200;			}
	}					sum += 200;
}					}

Here are some of what we think are the disadvantages and advantages of this
different definition:

Disadvantages:

This change would be incompatible with old C++ code.

The same thing can be accomplished by explicitly creating a block
surrounding the for statement, so why do it?

Advantages:

The same variable name can be used in multiple loops, and declared in each.
This makes loops less context-dependent.

If the variable needs to be used outside the loop, it must be declared
before the for statement.  This is more explicit, and easier to read.

Old code that changes in meaning will usually result in compiler errors,
unless another variable by the same name already exists (such as a global
variable).
___
A joint posting from:
 Nevin Liber (AT&T)  ..!ihnp4!ihlpf!nevin1 (send all email here; I will forward)
 Darin Adler (Apple) ..!sun!apple!darin
These are our own personal opinions, and (probably) not those of AT&T nor Apple.