"for i:=0 to i" loop in Pascal - why does it work?

Viewed 891

I'm surprised nobody ask this yet, because it's something I noticed a long time ago.

Apparently, in Pascal, you can use the same variable for both a loop counter, and a number of repetitions. The following two pieces of code:

i := 10;
for i:= 0 to i do
begin;
    write(i);
end;

and

for i:= 0 to 10 do
begin;
    write(i);
end;

appear to be equivalent, as both print 012345678910.

Why does it work, and why doesn't it work in other languages?

1 Answers

This works because, in Pascal, the end value of the loop is only evaluated once, i.e. the value of i is taken at the time the loop is entered.

In other words, the Pascal code is as if you had done:

someHelpVar := i;
for i := 0 to someHelpVar do

and that, in its turn, is equivalent to:

someHelpVar := i;
i := 0;
while i <= someHelpVar do
begin
  ...
  i := i + 1; // or Inc(i);
end;

In other languages, e.g. C, if you do:

for (i = 0; i <= i; i++)

you are not doing the same. The end value is re-evaluated on each iteration, i.e. not only once. The code above is like:

i = 0;
while (i <= i)
{
    ...
    i++;
}

Since that while condition is always true, you get an endless loop.


So, to summarize: in Pascal, the end value is evaluated only once and stored in an unnamed temporary variable. This means that the end condition does not change with i. In other languages, it is re-evaluated on each iteration, and not only once.

Note:

Doing something like

  i := 10;
  for i := 0 to i do

is frowned upon, because even though it works, it is confusing for the reader. Rather use a different variable as the loop index:

var
  i, j: Integer;
begin
  i := 10;
  for j := 0 to i do

As they say: "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability." Source: https://groups.google.com/d/msg/comp.lang.c++/rYCO5yn4lXw/oITtSkZOtoUJ

Related