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.

 

Last updated 2014-07-19T15:44:11+00:00.

Links to the standard

A discussion of the range-based for can be found in section 6.5.4. The more familiar for statement is discussed immediately prior in 6.5.3.

Benefits

The most common type of for-iteration now has a cleaner representation.

Risks

The traditional for statement is not going away. It is far more flexible in its possible representations, and C++ code will now have both varieties. Note that this leaves C++ much like the other languages that offer flavors of for.