The use of the term for
to designate counting loops likely evolved from the use of für
in Superplan. It has caught on in most programming languages, but is it the most appropriate term for a loop? The problem with the widely adapted for
is that it is just not expressive. Consider the use of for
in the following C statement:
for (x=1; x<=1000; x=x+1){
...
}
What it does is imply that x
has the values 1→1000, but it doesn’t really suggest something will be done. That this is implied by including a statement after the fact is fine, but it isn’t as obvious. The use of for
in a loop really implies that it is “used as a function word to indicate an actual or implied enumeration or selection“. It should really be used with the term do
, to imply something is being implemented. Likely the design of C assumed this, and just truncated the word do
, yet this lessens the readability of the loop.
The first decisive use of for
as a loop qualifier likely came in ALGOL-60.
for x := 1 step 1 until 1000 do
begin
...
end
However the loop still uses the verb do
to imply something will be done. Using for
by itself does not really imply a loop is to occur, at least from the perspective of descriptive terms. It is this reason that novice programmers learning C have difficulty with loops (well that and the obscure nature of the for
loop statement in C). Consider instead the Fortran version of the loop:
do x = 1,1000
...
end do
The term do
does imply that something will be done. The “x=1,1000
” just assigns constraints on the loop variable.
Maybe a better term would be one that suggests repetition is to be performed: loop
(Ada) , or repeat
(Pascal) perhaps? In Ada the for
loop setup certainly begins with for
, but ends with the keyword loop
, and the loop itself is terminated with the phrase end loop
. This is the same for the while
loop, and the generic loop
. Here is the sample for loop in Ada:
for x in 1 .. 1000 loop
...
end loop
An even better idea would be to create a structure which indicates it is a loop directly, with differing constraints. For example the term loop
used by Ada is a good starting point. From a computing point-of-view a loop implies repetition.
loop with x=1..1000
...
end loop
The use of the preposition with
helps to express the spatial relationship of the variable controlling the loop. It is also easy to extend this one piece of syntax to a family of loops. For example:
loop while x<1000
...
end loop
loop until x < 0
...
end loop
The choices made for control structures can have a great impact on the learnability of a language. The use of the term do
as in Fortran, implies something is to be done.