D Documentation  
For statement
for ( /* initializer */ ; /* test */ ; /* increment */ )
  statement;


The for loop is commonly used for executing a statement a certain number of times, but as it's syntax is very flexible it can be used for almost all kinds of loops.

It works by first executing the initializer, which can also be used to declare new variables - variable declared here have the scope of just that for loop, what means they will be available only during the test, the increment and the statement.

Second, it evaluates the test statement, and if it is true it executes the loop statement, followed by the increment statement.

This may sound a bit complex at first, but it's kind of simple. Just look at that code:
for ( int i = 0; i < 100; i++ )
{
  writef("i is now %d\n", i);
}

Note: The writef function just outputs the string and replaces %d by the value of i.

You can read that as: Set i to zero, count i up as long as it is smaller than 100 and execute the "writef..." block for each i.
If you execute this code it will print "i is now 0", "i is now 1", "i is now 2" and so on until "i is now 99". It'll never print "i is now 100" because of the test statement that says that i should be smaller than 100.

The for loop is equivalent to:
{
  /* initializer */
  while ( /* test */ )
  {
    statement;
    /* increment */
  }
}

Therefore you can abuse it as a while loop when you just leave the initializer and the increment empty.

Of course you can use the for loop in lots of other ways. Look at this:
char[] str = "aaaaaabcdef";
for (int i = 0; str[i] == 'a'; i++)
{
}

Note: This code is "unsafe" as it doesn't check array bounds! If there are just 'a'-characters in the string it'll try to read beyond the end of the string!

This says: set i to 0, and as long as the i-th character in str is an 'a' just increment i. This will search your string for the first non-'a' character. An empty loop statement is allowed as long as you use the curly braces, i.e. you can not just write:
for (int i = 0; str[i] == 'a'; i++)
  ;  /* illegal !!! */

Created using PHP docwiki written by Markus Dangl. Best viewed with Mozilla Firefox.