For

From Game Editor

Jump to: navigation, search

The for statement, like the do and while statements, is used to execute a block of code repeatedly.

The syntax of the for statement is like this:

for ( initialization ; test expression; update expression )
  statement;

The loop action, or body, may consist of a single statement without braces or one or more lines surrounded by braces.

for ( initialization ; test expression; update expression )
{
  statement 1;
  statement 2;
}

The initialization, test expression, update expression are optional.

This is an infinite for loop.

 for ( ; ; )
   statement;

The code in statement would be executed until a break statement was executed.

The initialization is a statement used to initialize the loop. It is evaluated once and only once. It is most often used to set the value of a variable to control the loop in test expression.

Example:

 for ( x = 0; ; )
   statement;

You can include multiple initializations with the Comma operator, like this:

 for ( x = 0, y = 0, z = 0; ; )
   statement;

The test expression is a statement used to test for continued looping. If test expression evaluates to true, the loop executes again. The test expression is evaluated before a loop.

Example

 for ( x = 0; x > 1 ; )
   statement;

In this example, the loop would NOT execute because x is initialized to the value 0 before it is tested. The test x > 1 would be false and the loop would not execute even once.

Example:

 for ( x = 1; x < 10 ; )
   statement;

In this example, the for loop would execute until the expression x < 10 is false.

The update expression is executed after the first loop, and before each additional loop test.

Example:

 for ( x = 1; x < 10 ; ++ x)
   statement;

This example would execute statement until x < 10 fails. Since x is initialized to 1 and the update expression adds one to x after each loop, the loop would execute 9 times.

Retrieved from "http://game-editor.com/For"