For Statement Example
Previous Topic  Next Topic 

A for_statement it is usually used to iterate over a range of values where the start_expr_list to initialises some variables that are then checked in the conditional expression.   The end_expr_list is evaluated at the end of each iteration of the loop and usually increments or decrements the variables that are checked in the conditional expression.


For example:


myarray[0..9];

// Loop from i=0 through to i=9 setting all elements of array to -1

for(i=0;i<10;i++)

    // Set element i of array to -1

    myarray[i]=-1;

endfor


// i will be equal to 10 at this point in the code..

...


Heres another example where the start_expr_list contains two expressions (separated by comma) but there is no expression in the end_expr_list


// start and end expressions can have multiple expressions or none at all...

for(i=0,j=10; i <= 100; )

      applog("i=",i," j=",j);

      j++; 

      i=i+j;     // This could have gone into the end_expr_list

endfor



If the conditional expression of a for_statement is left blank then the conditional expression will always equated to true so the loop will loop indefinitely.  For example:


// this will loop forever

for(i=0;;i++)

    applog("i=",i);

endfor


Note than this is special syntax for the for_statement only, empty conditional expressions are not allowed in while_statements or do_statements.