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

后端 未结 4 1551
终归单人心
终归单人心 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 07:59

    You're under a misconception that a ranged-for needs to know the number of iterations (the "length") in advance. It does not.

    It does need a termination condition, which has the form it != __end where __end = x.end() or __end = end(x).

    Of course, arrays can't change their size, so in this one case detecting the end and knowing the length are equivalent (length can be gotten from begin, end, and pointer subtraction).

    As Oli mentioned in the comments, the type of an array does contain length information, and std::end uses an array reference for its parameter, to avoid the decay to pointer which loses this information.

    The definition is basically:

    namespace std
    {
        template 
        T* end(T (&array)[N])
        {
            return array + N;
            // or if you want to be cute
            // return 1[&array];
        }
    }
    

    When the bound in an array reference is a non-type template parameter, it is deducible. Use this to your advantage when writing functions that accept arrays.

    (The compiler actually has the array + N calculation for the end built-in for arrays, it doesn't use std::end() for that. But there would be no difference after inlining anyway, and it's useful to see how you can play the same trick the compiler does.)

提交回复
热议问题