cpp/language/range-for

Executes a for loop over a range.

Used as a more readable equivalent to the traditional operating over a range of values, such as all elements in a container.

Explanation
The above syntax produces code equivalent to the following. The variables ', ' and  are for exposition only.

is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and is used to initialize the variable with the type and name given in.

' and ' are defined as follows:
 * If is an expression of array type, then ' is  and ' is, where  is the number of elements in the array (if the array has unknown size or is of an incomplete type, the program is ill-formed);
 * If is an expression of a class type  that has both a member named  and a member named  (regardless of the type or accessibility of such member), then ' is  and ' is ;
 * Otherwise, ' is and ' is, which are found via  (non-ADL lookup is not performed).

Just as with a traditional loop, a can be used to exit the loop early and a  can be used to restart the loop with the next element.

If a name introduced in is redeclared in the outermost block of, the program is ill-formed:

Temporary range expression
If returns a temporary, its lifetime is extended until the end of the loop, as indicated by binding to the forwarding reference . Lifetimes of all temporaries within are  extended.