For loop

From ZCWiki
Jump to navigationJump to search

Use the for loop when you want certain things to happen a certain number of times.

Syntax and Execution

The for loop has the following syntax:

for(initial-count; test-expression; update-count){ 
  // statements inside the curly braces
  // are only executed if test-expression
  // is true.


  • initial-count intializes the value of the counter used by the loop; the counter is simply a variable. The counter is intialized only once, when the loop first starts.
  • test-expression checks the current value of the counter against some other value. This is done at the beginning of each iteration of the loop. The loop is terminated if the test-expression evaluates to false. If test-expression evaluates to true, then the statements inside the braces are executed and test-expression is checked again at the start of the next iteration.
  • update-count updates the value of the counter after each iteration of the loop.

For example, the following for loop writes the value of the variable count to the logfile 10 times.

int count;
for(count = 1; count <= 10; count++){

count is initialized to 1. Then the check occurs: is count less than or equal to 10? It is, so the Trace function is called. Then count is incremented to 2, and the check occurs again...and so on, until count becomes 11, and the loop is terminated. Note again that the counter is initialized only once, and the counter is updated at the end of each iteration, before it is checked at the beginning of the next iteration.

Since test-expression is checked at the beginning of the loop, it is possible that the statements in the braces will never be executed (that is, if test-expression evaluates to false the first time the for loop is encountered, nothing in the loop will be executed). This is typically more of a problem with while loops than for loops, though if you incorrectly initialize your counter it could happen.

While typically the update-count expression is the only means by which you will need to update the counter, there is nothing preventing you from altering the value of the counter inside the for loop.

The update-count expression is not limited to simple increments. For instance, the following for loop is valid:

int count;
for(count = 100; count > 1; count = count / 2){

It produces the following in the allegro.log file:


See Also