Daniel Robertson
Daniel Robertson

Reputation: 1394

What is the difference between the C++ array operator and *(array + index) if any?

I frequently use code like the following to index items out of arrays just to remind myself that the array value is a pointer to the first element of the array.

int array[] = {0,1,2,3,4,5};
*(array + 2) = 42;

While it looks a little ugly, from time to time I actually prefer it to the traditional [] operator.

int array[] = {0,1,2,3,4,5};
array[2] = 42;

Other than making other people who may read my code in the future a little angry, are there any consequences to using pointer arithmetic to index an array over the [] operator?

Upvotes: 1

Views: 586

Answers (3)

Nemo
Nemo

Reputation: 71525

Section 5.2.1 [expr.sub] of the C++ spec says:

... The expression E1[E2] is identical (by definition) to *((E1)+(E2))

So they are exactly the same, by definition.

See http://www.open-std.org/jtc1/sc22/open/n2356/expr.html#expr.sub for an older version of the spec. The same wording appears in all of them.

[Update]

Note that "the array value is a pointer to the first element of the array" is not exactly true, as sizeof(array) (among other things) will demonstrate. The array decays to a pointer in many contexts, but that is not the same thing. So I would say your style choice here is simply confusing, to other people and even to yourself... Plus you are violating the very common and useful "container access" abstraction, as other commenters point out. That is, you are ruling out replacing the array with a std::vector or std::deque or really any other container. Just poor style, IMO.

Upvotes: 10

T.C.
T.C.

Reputation: 137320

The built-in [] operator is defined in terms of + and *.

That is, a[b], where [] is the built-in operator, is exactly equivalent to *(a+b). This also allows you to write such gems as 2[array] or 3["hello"] or 0[this].

Obviously, for overloaded operators, there's no such equivalence.

Upvotes: 4

halfflat
halfflat

Reputation: 1584

For an array, there is no difference. It doesn't extend well to other containers, though, so refactoring code written with this equivalence in mind to use, for example, a std::vector will require much more effort.

Upvotes: 4

Related Questions