| for | Keyword

Keyword Index

For loop.

For-loop is yet another kind of loop. It uses `for` keyword, with the following syntax:

    for ([expr1]; [expr2]; [expr3]) statement

statement is executed repeatedly until the value of expr2 is 0. Before the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop. After each iteration of the loop, expr3 is evaluated. This is usually used to increment a loop counter. In fact, the for-loop is absolutely equivalent to the following sequence of statements:

    expr1;
    while (expr2)
      {
        statement;
        expr3;
      }

That's why expr1 and expr3 must contain side effects, else they are useless. For example,

    for (i=0; i<100; i++) sum += x[i];

    for (i=0, t=string; i<40 && *t; i++, t++) putch(*t);
    putch('\n');

    for (i=0, sum=0, sumsq=0, i<100; i++)
      {
        sum += i; sumsq += i*i;
      }

All the expressions are optional. If expr2 is left out, it is assumed to be 1. statement may be a compound statement as well.