Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, do dereferencing and getting index zero do the same tihng?

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?

like image 398
eje211 Avatar asked Apr 11 '16 20:04

eje211


3 Answers

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.

like image 102
T.C. Avatar answered Oct 15 '22 01:10

T.C.


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.

like image 34
AlexD Avatar answered Oct 15 '22 02:10

AlexD


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).

like image 35
fuzzything44 Avatar answered Oct 15 '22 02:10

fuzzything44