Back: 1.2.4.1 The while and do while statements Forward: 1.2.4.3 Using break, continue, and goto     FastBack: 1. Basic Ideas Up: 1.2.4 Loops FastForward: 2. Using Array Syntax         Top: Yorick: An Interpreted Language Contents: Table of Contents     About: About This Document

1.2.4.2 The for statement

The for statement is a “packaged” form of a while loop. The meaning of this generic for statement is the same as the following while:

 
for (start_statements ; condition ; step_statements) body_statements

start_statments
while (condition) {
  body_statements
  step_statements
}

There only two reasons to prefer for over while: Most importantly, for can show “up front” how a loop index is initialized and incremented, rather than relegating the increment operation (step_statements) to the end of the loop. Secondly, the continue statement (see goto) branches just past the body of the loop, which would include the step_statements in a while loop, but not in a for loop.

In order to make Yorick loop syntax agree with C, Yorick’s for statement has a syntactic irregularity: If the start_statements and step_statements consist of more than one statement, then commas (not semicolons) separate the statements. (The C comma operator is not available in any other context in Yorick.) The two semicolons separate the start, condition, and step clauses and must always be present, but any or all of the three clauses themselves may be blank. For example, in order to increment two variables i and j, a loop might look like this:

 
for (i=1000, j=1 ; i>j ; i+=1000, j*=2);

This example also illustrates that the body_statements may be omitted; the point of this loop is merely to compute the first i and j for which the condition is not satisfied. The trailing semicolon is necessary in this case, since otherwise the line would be continued (on the assumption that the loop body was to follow).

The += and *= are special forms of the = operator; i=i+1000 and j=j*2 mean the same thing. Any binary operator may be used in this short-hand form in order to increment a variable. Like ++i and --i, these are particularly useful in loop increment expressions.


Back: 1.2.4.1 The while and do while statements Forward: 1.2.4.3 Using break, continue, and goto     FastBack: 1. Basic Ideas Up: 1.2.4 Loops FastForward: 2. Using Array Syntax         Top: Yorick: An Interpreted Language Contents: Table of Contents     About: About This Document