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:
- It evaluates the array_expression which must return an array.
- If the array is empty, exit the loop.
- It then assigns the first element from the array to the variable.
- Then it executes the statement.
- If there are more elements in the array, the next one is assigned to
the variable, otherwise exit the loop.
- 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;
}