How does std::end know the end of an array?

But, how does it know the end of an array

It uses a template non-type parameter to deduce the size of the array, which can then be used to produce the end pointer. The C++11 signature from the cppreference section for std::end is as follows:

template< class T, std::size_t N >
T* end( T (&array)[N] );

As hvd notes, since it is passed by reference this prevents decay to a pointer.

The implementation would be something similar to:

template< class T, std::size_t N >
T* end( T (&array)[N] )
{
    return array + N ;
}

Is the constant integer 5 will be stored some where?

5 or N is part of the type of the array and so N is available at compile time. For example applying sizeof to an array will give us the total number of bytes in the array.

Many times we see an array passed by value to a function. In that case, the array decays to a pointer to type stored in the array. So now the size information is lost. Passing by reference allows us to avoid this loss of information and extract the size N from the type.

Leave a Comment