I was looking at the following example from http://www.cplusplus.com/doc/tutorial/arrays/ and I couldn\'t figure out how the 2nd for loop worked. How can the for loop know w
The reason this works is that the for
loop effectively1 uses std::begin
and std::end
. Those, in turn, work, because they provide overloads specifically for built-in arrays, something like this:
template
T *begin(T (&array)[N]) {
return array;
}
template
T *end(T (&array)[N]) {
return array+N;
}
Although it (apparently) hadn't been realized before the original (1998) C++ standard was published, this technique doesn't require any language features beyond those available in C++98. C++11 codified the technique and puts it to use.
Since, in this case, the parameter is specified as a reference to an array, type deduction will only succeed when the parameter really is an array. In the case of std::begin
, there are also versions that support other parameter types and use (for example) the begin()
and end()
members of collections, if that type is matched.
1. "Effectively" in this case meaning there are some circumstances in which a range-based for loop uses begin
and end
, and others in which they're not. If you're into technicalities, they're not used for arrays, but a similar computation is done directly. Likewise, for container types that have begin
and end
members, those are used directly. If neither of those is true, then begin(range)
and end(range)
are used, which can use either std::begin
/std::end
, or a begin(x)
/end(x)
pair found by argument dependent lookup.