Next: Error-Handling Statements
Prev: Conditional Statements
C-- provides three kinds of looping statements. These statements
allow you to traverse a list or a range of numbers, or to execute a
statement as long as a certain condition is true. C-- also
provides two kinds of jump statements which allow you to prematurely
exit from a loop or continue onto the next iteration.
The for-list statement allows you to traverse a list. It has the following syntax:
for variable in (list)
statement
variable must be the name of a local variable, and list must
be an expression of list type. The interpreter executes statement
once for each element of list. variable contains the list
element that the interpreter is at. Here is an example of a method
using a for-list statement:
var a, s;You can also iterate over the associations in a dictionary with the for-list statement; see Dictionaries.a = ["foo", "bar", "baz"]; for s in (a) .tell(s);
The for-range statement allows you to traverse a range of integers. It has the following syntax:
for variable in [lower .. upper]
statement
As before, variable must be the name of a local variable.
lower and upper must be expressions of integer type. The
interpreter executes statement once for each number from
lower to upper inclusive. variable contains the
number that the interpreter is at. Assigning to variable within
the loop body will not change the status of the loop; the interpreter
remembers what number it is at independently of the loop index. Here is
an example of a method using a for-range statement:
var i;The while statement allows you to execute code as long as a condition expression is true. The while statement has the following syntax:for i in [1 .. 10] .tell(tostr(i));
while (expression)
statement
The interpreter continually evaluates expression and executes
statement until the value of expression is false, according
to the rules in Data Types. Here is an example of a method using
a while statement:
var a;The break statement allows you to exit a loop prematurely. The break statement has the following syntax:a = 1; while (a < 35) a = a * 2; .tell(tostr(a));
break;The interpreter jumps to the end of the innermost for-list, for-range, or while statement.
The continue statement allows you to jump to the next iteration of a loop. The continue statement has the following syntax:
continue;The interpreter skips the remainder of the loop body and begins another iteration of the innermost for-list, for-range, or while statement.
The break and continue statements do not allow you to break out of two
loops at once. C-- does not provide any general jump mechanism.
If you find that you require jumps other than break or continue
statements, then you probably need to reorganize your code.