Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the C++ begin and end work when argument is an array? [duplicate]

Tags:

c++

arrays

stl

A problem in C++ primer, when begin and end work on vector I know there is vector::size() could help, but how do they work when I just give an array argument. just like:

int arr[] = {1, 2, 3};
size = end(arr) - begin(arr);

how do end(arr) and begin(arr) work correctly ?

like image 580
alexxx Avatar asked Nov 09 '15 02:11

alexxx


People also ask

How does C know when an array ends?

C arrays don't have an end marker. It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size. If you do access an element outside the allocated size, the result is undefined behaviour.

When you pass an array as an argument to a function what actually gets passed?

Explanation: The statement 'C' is correct. When we pass an array as a funtion argument, the base address of the array will be passed.

Can we pass array as argument in C?

Passing Array to Function in C/C++ Just like normal variables, simple arrays can also be passed to a function as an argument, but in C/C++ whenever we pass an array as a function argument then it is always treated as a pointer by a function.

How is an array passed to a function in C?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.


2 Answers

So to see how std::end works we can look at How does std::end know the end of an array? and see that the signature for std::end is:

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

and it is using template non-type parameter to deduce the size of the array and it is just a matter of pointer arithmetic to obtain the end:

return array + N ;

For std::begin the signature is identical, with the exception of the name:

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

and calculating the beginning of the array is simply a matter of array to pointer decay which gives us a pointer to the first element of the array.

In C++14 these both become constexpr.

like image 183
Shafik Yaghmour Avatar answered Oct 12 '22 23:10

Shafik Yaghmour


I'll just paste a piece of code from here

template <class _Tp, size_t _Np>
inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
_Tp*
begin(_Tp (&__array)[_Np])
{
    return __array;
}

template <class _Tp, size_t _Np>
inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
_Tp*
end(_Tp (&__array)[_Np])
{
    return __array + _Np;
}
like image 38
Xiaotian Pei Avatar answered Oct 13 '22 00:10

Xiaotian Pei