For Statement Definition
Previous Topic  Next Topic 

The for_statement is similar to a while_statement except that a comma separated list of expressions are allowed for initialiation of the loop variables (start_expr_list) and another comma separated list of expressions which are excecuted at the end of each loop iteration (the end_expr_list).      The syntax of the for loop is as follows:


for ( {start_expr_list } ; { expr }; { end_expr_list })

     statement_block

endfor


The start_expr_list is a comma separated list of zero or more expressions that are evaluated before the first iteration of the loop, and the end_expr_list is a comma separated list of zero or more expressions that are evaluated at the end of each iteration of the loop.     The sytax definition for start_expr_list and end_expr_list is as follows:


expr {, expr {,...}}


The start_expr_list is usually used to initialise some variables that are tested in the conditional expression of the loop, and the end_expr_list is usually used to increment or decrement these variables so the loop only executes a certain number of times.


The for_statement is similar to the  while_statement in that the  statement_block will continue to be executed until the the conditional expression evaluates to 0 (zero) .


However, notice from the for_statement definition that the start_expr_list, conditional expression (expr) and end_expr_list are all optional.   If the conditional expression is left blank in a for_statement then this always equates to true.      For example the following is perfectly valid and creates an infinite loop:


for(;;)

   applog("Looping to infinity and beyond");

endfor



This is not the same for a while_statement or do_statement.    In those loops it is illegal to have a blank conditional expression.


// This is illegal!

while()

   do_something();

endwhile



// This is illegal!

do

   something();

until();