Previous section To contents

3.2.4 foreach

Foreach is unique in that it does not have an explicit test expression evaluated for each iteration in the loop. Instead, foreach executes the statement once for each element in an array. Foreach looks like this:
foreach ( array_expression, variable )
    statement ;
We have already seen an example of foreach in the find_song function in chapter 2. What foreach does is:
  1. It evaluates the array_expression which must return an array.
  2. If the array is empty, exit the loop.
  3. It then assigns the first element from the array to the variable.
  4. Then it executes the statement.
  5. If there are more elements in the array, the next one is assigned to the variable, otherwise exit the loop.
  6. Go to point 4.
Foreach is not really necessary, but it is faster and clearer than doing the same thing with a for loop, as shown here:
array tmp1= array_expression;
for ( tmp2 = 0; tmp2 < sizeof(tmp1); tmp2++ )
{
    variable = tmp1 [ tmp2 ];
    statement;
}


Previous section To contents