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 compiler knows the number of elements of the array due to the array definition. So it uses expressions myarray
and myarray + 3
to traverse the array.
In fact the loop looks the following way
for ( auto first = myarray, last = myarray + 3; first != last; ++first )
{
auto elem = *first;
cout << elem << '\n';
}
Take into account that the range-based for statement use neither std::begin() nor std::end() for arrays as others wrote here.:)
According to the C++ Standard
— if _RangeT is an array type, begin-expr and end-expr are __range and __range + __bound, respectively, where __bound is the array bound. If _RangeT is an array of unknown size or an array of incomplete type, the program is ill-formed;