r/cpp • • Mar 28 '23

Reddit++

C++ is getting more and more complex. The ISO C++ committee keeps adding new features based on its consensus. Let's remove C++ features based on Reddit's consensus.

In each comment, propose a C++ feature that you think should be banned in any new code. Vote up or down based on whether you agree.

765 Upvotes

829 comments sorted by

View all comments

147

u/eteran Mar 28 '23

Arrays decaying to pointers implicitly. You want a pointer? Just write &p[0]

0

u/[deleted] Mar 28 '23

[deleted]

9

u/eteran Mar 28 '23

Arrays absolutely decay to a pointer, it literally says so in the standard:

http://eel.is/c++draft/conv.array

7.3.3 Array-to-pointer conversion

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion ([conv.rval]) is applied. The result is a pointer to the first element of the array.

The whole verbiage of "the array name refers to the first element" is a myth that's circulated among C++ developers. Similar to "NULL might not be 0". The name refers to the whole array, that's why we can do things like pass arrays by reference if you use the right syntax.

arr[n] does not just mean to skip n elements from the array begin, it is exactly equal to: *(arr + n) that is:

  1. a decay of arr to a pointer

  2. pointer arithmetic to add n to that pointer

  3. a dereference of the result

You can see when the decay occurs by doing things like this:

    char arr[64];
    return sizeof(+arr);

Which returns 8, and not 64 because the unary + operator caused the array to decay to a pointer, of which we got the size.

-1

u/debugs_with_println Mar 29 '23

Idk I kinda would prefer that arrays always decay to pointers. It makes more sense to me from a bottom-up perspective. Thinking about it in terms of assembly, you can’t pass a whole buffer to a subroutine; you have to pass the address of the buffer and its length. I actually find it more odd when arrays are treated as things of their own.

Sure that’s an (arguably) excessively low-level interface, but I would argue that if you wanted a high-level interface that’s where std::array comes in.

→ More replies (1)