How does a “for each” loop in C++ know the length of an array

后端 未结 4 1550
终归单人心
终归单人心 2021-01-13 07:15

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

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-13 08:12

    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;

提交回复
热议问题