TITLE: why change the scope of loop variables


[ This discussion centers on the code below, in particular, the scope
  of the variable "i". 

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

  - adc ]


RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 6 Dec 95

It's actually a little more complicated than that. The rule in the ARM is
that the scope of a variable declared in a 'for' is the scope in which
the 'for' appears. That is, for example,
	{
		for(int j = 0; ... ; ... ) {
			... can use j here
		}
		... can use j here
	}
	... j now out of scope

One problem with that rule was that is was inconvenient to write code like

	for(int j = 0; ... ; ... ) {
	}
	...
	for(int j = 0; ... ; ... ) { // error, multiple definition of j
	}

You have to change the second loop to
	for(j = 0; ... ; )
but if you delete the first loop, the second one is now in error. In
addition, it seems odd for the loops to look different. This complexity
made the ability to declare a loop variable somewhat pointless.

Worse, the ARM did not cover this case:
	for(int i = 0; ... ; ... )	// no braces here
		for(int j = 0; ... ; ... )
What is the scope of j? The ARM didn't say, compilers behaved differently,
and there didn't seem to be an obviously correct answer.
			
Thus, the rule was changed to limit the scope of the loop variable to
the loop itself, uniformly. Not all compilers implement the new rule yet.


