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!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|