http://www.perlmonks.org?node_id=317485


in reply to Re: Re: for loop localisation bug?
in thread for loop localisation bug?

I beg to differ, at least as far as C is concerned.

#include <stdio.h> void main() { int n; for( n=0; n<10; n++ ) { printf( "%d\n", n ); if( n == 5 ) break; } printf( "Residual value: %d\n", n ); } __END__ P:\test>bcc32 test.c Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland test.c: Turbo Incremental Link 5.00 Copyright (c) 1997, 2000 Borland P:\test>test 0 1 2 3 4 5 Residual value: 5

And even in languages that allow the loop variable to be declared within the for loop initialiser statement, it's scope is not that of the for loop body, but that of the enclosing block.

From p.38 of "Programming in C++ by Stephen C. Dewhurst & Kathy T. Stark"

Declarations are statements and can appear any place a statement can within a block. This flexibility allows names to be declared and initialised at the point of their first use. For example, the first clause in a for loop control is a statement so a loop index can be declared there.
for( int i = 0; i < limit; i++ ) { // etc. } return i;

The scope of the name extends from its point of declaration to the end of the enclosing block. Notice that in this example, i is still available after the loop terminates. It goes out of scope at the end of the block that contains the for statement.

I don't have a Pascal reference handy, but I seem to recall (from a very long time ago) that it's for loop acted similarly.


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
Hooray!