In C++11 you can use a range-based for, which acts as the foreach of other languages. It works even with plain C arrays:
int numbers[] = { 1, 2, 3, 4, 5 };
for (int& n : numbers) {
n *= 2;
}
How does it know when to stop? Does it only work with static arrays that have been declared in the same scope the for is used in? How would you use this for with dynamic arrays?
It works for any expression whose type is an array. For example:
For a more detailed explanation, if the type of the expression passed to the right of
:is an array type, then the loop iterates fromptrtoptr + size(ptrpointing to the first element of the array,sizebeing the element count of the array).This is in contrast to user defined types, which work by looking up
beginandendas members if you pass a class object or (if there is no members called that way) non-member functions. Those functions will yield the begin and end iterators (pointing to directly after the last element and the begin of the sequence respectively).This question clears up why that difference exists.