For Statement

next up previous contents index
Next: Break Statement Up: Statements Previous: While Statement

For Statement

A for statement is used to invoke an iterator (6), and is the only way an iterator can be invoked. The iterator produces a sequence of items (where an item is a group of one or more objects) one item at a time; the body of the for statement is executed for each item in the sequence.

The for statement has the form

for <for_idns> in <invoc> do <body> end
<for_idns> -> <idn_list> | <decl> ["," <decl>]*
The loop variables are given first. Either a list of already-declared variables is given, or new loop variables local to the for statement are introduced using declarations. Previously declared variables cannot be mixed with new declarations. The invocation, given next, must be an invocation of an iterator.

The first loop variable is assigned the first object yielded in an item, etc.; the type of each yielded object (according to the specification of the iterator) must be a subtype of the type of the corresponding loop variable.

Execution of the for statement proceeds as follows. First the iterator is invoked, and it either yields an item or terminates. If the iterator yields an item, its execution is temporarily suspended, the objects in the item are assigned to the loop variables, and the body of the for statement is executed. The next cycle of the loop is begun by resuming execution of the iterator from its point of suspension. Whenever the iterator terminates, the entire for statement terminates. If the for statement terminates, this also terminates the iterator.

The following example creates an "array[int]" and appends the numbers 1 through 10 to it:

a: array[int] := array_new[int]()
for i: int in do
This example uses the "to" iterator method of int object 1 (B.4), which yields successively larger values starting with its object and ending with the argument.