for (range based)

Like most C++ programmers, I have little love for PHP, although I use it a lot to throw together web sites ... uh ... like this one. PHP does have one statement that I came to appreciate early on, the "foreach" statement. The good people at boost.org gave use their version of foreach, and there is the for_each algorithm in the STL, but it is now available as a part of the core language. This is as it should be.

The new statement is written something like this example from the ISO doc:

int array[5] = { 1, 2, 3, 4, 5 }; 
for (int & x : array)
  x *= 2;
     

This is a condensation of the usual, and more wordy way we write these things:

int array[5] = { 1, 2, 3, 4, 5 }; 
for (unsigned int j = 0; 
     j < sizeof(array)/sizeof(*array); 
     j++)
  array[j] *= 2;
     

The ISO example makes an important point; the iterative container must be assignment compatible with elements of the range, which is why x is a reference to int, and not an int. Something like this:

int array[5] = { 1, 2, 3, 4, 5 }; 
for (int x : array)
  x *= 2;
     

would not modify the contents of array, so be careful.