lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 5-Oct-05, at 4:38 AM, David Given wrote:

As another data point:

C++ (and now C99) allows you to declare loop variables inside loop statements:

for (int i=0; i<10; i++)
{
	printf("%d\n", i);
}

It's interesting to note that old versions of the standard decreed that the scope of the loop variable extended until the end of the enclosing scope;
that is, it was equivalent to:

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

However, the standard then changed so that the scope was limited to the for()
block only.

Saying that the standard changed is a bit of a stretch. Bjarne Stroustrup's original definition of C++ had the "scope extends to end of enclosing scope" rule, but very early in the standardisation process (1995, as far as I can see), and long before the standard was adopted, the standardisation committee agreed on the "scope is the loop itself" semantics. So "the standard" itself never changed, although the standard was a change to the original ARM (and of course there were other changes as well).

D&E only says that the debate was extensive, and I certainly wasn't part of it, but it is possible to imagine a number of reasons why you would want the scope. Some of these are mentioned (with respect to C) in this thread: <http://groups.google.com/group/comp.std.c/browse_frm/thread/ 1e00a56a898a3b9c/>

Here are some of the reasons, in no particular order:

1) If you wanted the scope of the variables to extend to the end of the enclosing scope, you can just put the declaration outside the for statement. Making the scope of the variables the same as the scope of the loop is more difficult, so the new syntax ought to add something.

2) If you want to define a macro which creates a loop, you don't want to pollute the namespace of the macro call-site

3) Some optimisations are easier to do if you know that the control variable's scope is limited to the loop.