In C ++, do dereferences dereference and get a zero index?

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 the null index of any pointer, I get a value of the correct type at the location of the pointer. Isn't that the same thing as acting out?

Every time a pointer is dereferenced in C ++, will it not get a null index? I do not suggest that anyone actually do this, but I think it will work. Is not it?

+6
source share
3 answers

Ignoring overloaded operators, there is one case there is a difference, and this array is 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 do not know any compiler that implements this permission. But this must be realized in the end.

+11
source

Assuming the operator is not overloaded, they are almost the same.

[C] 6.5.2.1 Substring of an array :

E1[E2] is identical (*((E1)+(E2)))

[C ++] 5.2.1 Signature :

The expression E1[E2] identical (by definition) to *((E1)+(E2)) ..., except that in the case of an operand of an array, the result is an lvalue if this operand is an lvalue and xvalue otherwise.

Note the excellent @TC answer regarding the last part.

+7
source

For pointers, they should give the same result.

The only time they can be different is that you apply them to a custom type that overloads operator*() and operator[](int) differently (or one, not the other, in which case you will get compilation error).

+4
source

All Articles