Search code examples
c++pointersdereference

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?


Solution

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