Nick Keighley <ni************ ******@hotmail. comwrites:
[...]
some languages make it UB to acces the for loop variable
outside the loop (I think- Pascal, Alogol-60 and Ada)
but I think it is guaranteed to point one past the end
of the array after exiting from a "normal" for-loop.
(I can't be arsed to define the exit value in Standarese).
There's nothing magical about a C90-style for loop. A variable that
happens to be used in one or more of the for loop header's expressions
has whatever value it has after the loop terminates. This:
int i;
for (i = 0; i < 100; i ++) {
/* code that doesn't modify i */
}
printf("i = %d\n", i);
will print "i = 100".
C99 introduces the ability to define a variable in the loop header:
for (int i = 0; i < 100; i ++) { ... }
Referring to such a variable outside the loop isn't merely undefined
bhaevior, it's impossible. (Well, you could save its address in a
pointer variable; dereferencing the pointer outside the loop would
invoke undefined behavior.)
For comparison ...
<OT>
In Pascal, a for loop specifies a range. I *think* the value is
unspecified after the loop terminates, but I don't remember -- and it
probably varies among various implementations and pseudo-standards. I
don't know about Algol-60. Ada's for loop is much more restrictive
than C's:
for I in 0 .. 99 loop
...
end loop;
``I'' is treated as a constant (a non-modifiable object) within the
body of the loop, and doesn't exist outside the loop. You could take
its address and try to refer to it from outside the loop, as you can
in C, but Ada discourages that kind of thing; if you do it anyway, you
get Ada's equivalent of undefined behavior.
</OT>
--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"