I just tried this code:
int i = 33;
int * pi = &i;
cout << "i: " << *pi << endl;
cout << "i: " << pi[0] << endl;
Both lines return the same thing.
Essentially, if I get index zero of any pointer, I'll get the value of the correct type at the location of the pointer. Isn't that the same thing as dereferencing?
Every time a pointer is dereferenced in C++, wouldn't getting index zero also work? I'm not suggesting anyone should actually do that, but I think it would work. Wouldn't it?
Ignoring overloaded operators, there's one case there is a difference, and that's array rvalues post-DR1213:
using arr = int[2];
arr&& f();
int&& b = *f(); // error, *f() is an lvalue, doesn't bind to int&&
int&& c = f()[0]; // OK, subscript applied to array rvalue results in an xvalue
I don't know of any compiler that implements that resolution, though. But it should be implemented eventually.
Assuming no operator overloading, they are nearly the same.
[C] 6.5.2.1 Array subscripting:
E1[E2]
is identical to(*((E1)+(E2)))
[C++] 5.2.1 Subscripting:
The expression
E1[E2]
is identical (by definition) to*((E1)+(E2))
... , except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise.
See the great answer of @T.C regarding the last part.
For pointers, they should give the same result.
The only time that they could differ is if you are applying them on a user-defined type that overloads operator*()
and operator[](int)
differently (or one and not the other, in which case you would get a compile error).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With