Statements: for loop

The for loop iteration statement lets you repeat a nested statement a specified number of times.


Form 1:

for( ;condition;loop‑expressions)statement

Form 2:


Form 3:

for( ;; )statement


The for loop statement executes the nested statement repeatedly as long as the condition evaluates to the boolean value true. The condition is evaluated at the begin of every iteration. In turn, with the end of an iteration, the loop-expressions are evaluated. Usually, the loop-expressions are used to increment or decrement counter variables, etc.. For example:

array string text[ 16 ]; var int32 i = 0; // Initialize all 16 elements of the one-dimensional array for ( ; i < text.size; i = i + 1 ) text[ i ] = "";

In the second form of the for statement you can specify additional init-expressions, that are evaluated just before the first iteration begun. Usually, init-expressions are used to initialize counter variables. To execute multiple statements within the loop, you can group those together within a block statement. For example:

var int32 i; // Hide all text views existing within the current GUI component for ( i = CountViews(); i > 0; i = i - 1 ) { var Core::View view = GetViewAtIndex( i - 1 ); var Views::Text textView = (Views::Text)view; // Is this a text view? if ( textView != null ) textView.Visible = false; }

The for statement accepts in its init-expressions and loop-expressions multiple expressions separated by , (comma) signs. In this manner multiple counter variables can be initialized at once as well as multiple variables can be incremented with each loop iteration. In the following example, the for statement performs three initialization and two loop expressions:

var int32 a; var int32 b; var int32 c; for ( a = 0, b = 0, c = 0; a < 10; c = b, b = a++ ) { ... }

The for statement can be combined with the statements break and continue. break causes the loop to exit immediately passing the control to the next statement following for. In this case, the condition and loop-expressions are not evaluated. When continue statement is executed inside a loop, the control jumps to the beginning of the loop for next iteration, bypassing all following statements inside the body of loop for the current iteration. For example:

for ( inx = 0; inx < count; inx++ ) { var int32 v = Array[ inx ]; if ( v > 10 ) continue; if ( !v ) break; sum += math_pow( 2, v ); }

The third form of the for statement omits all expressions resulting in an unconditionally infinite loop. In order to avoid the loop to iterate endless please use the break statement to explicitly exit the loop. Following example demonstrates this application case:

// Endless loop for (;;) { ProcessCommand(); // Break the loop if all operations are done if ( !AnyFurtherCommand()) break; GetNextCommand(); }