Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

begin and end as non-member functions

42 views
Skip to first unread message

Paul

unread,
Apr 20, 2015, 8:54:16 AM4/20/15
to
Please can someone explain why the second version does not compile even though the first one does? The error is "no matching function for call to end(int*&)"

Thank you,

Paul


void testBeginEnd()
{
int a[] = {1, 2};
auto n = end(a) - begin(a);
}

void testBeginEnd(int a[] )
{
auto n = end(a) - begin(a);
}

Luca Risolia

unread,
Apr 20, 2015, 9:07:37 AM4/20/15
to
On 20/04/2015 14:53, Paul wrote:
> Please can someone explain why the second version does not compile even though the first one does? The error is "no matching function for call to end(int*&)"

because the array parameter "decays" into a pointer, for which there is
no matching end() function declared.

> void testBeginEnd(int a[] )

Juha Nieminen

unread,
Apr 20, 2015, 10:30:12 AM4/20/15
to
Paul <peps...@gmail.com> wrote:
> void testBeginEnd()
> {
> int a[] = {1, 2};
> auto n = end(a) - begin(a);
> }

Here 'a' is a static array, not a pointer. Thus std::begin() and std::end()
work fine with it.

> void testBeginEnd(int a[] )
> {
> auto n = end(a) - begin(a);
> }

Here 'a' is a pointer, not a static array, thus they don't work with it.

The syntax you used doesn't mean "static array". It means "pointer".
To receive a static array as parameter you have to use a different
syntax:

void testBeginEnd(int (&a)[2])

(Although note that the entire array is not passed to the function,
but rather a reference to the original array.)

--- news://freenews.netfront.net/ - complaints: ne...@netfront.net ---

Victor Bazarov

unread,
Apr 20, 2015, 10:46:08 AM4/20/15
to
Just a nit-pick... Neither in the former example, nor in the latter
declaration, the array is *static*. While severely overloaded, the term
'static' has nonetheless specific meaning that doesn't apply here, I think.

It is better to use the term "an array of a known dimension" instead of
"static array" in such explanations. In a declaration "foo(int a[])"
the argument is "an array of unknown dimension", which inturnally (a pun
on "in turn", he-he) is converted into a pointer, as you already pointed
out.

V
--
I do not respond to top-posted replies, please don't ask
0 new messages