How does operator [] of an address of variable work?

for example:

int x = 5;
std::cout<<(&x)[0]<<std::endl; -> prints 5

i found this representation of 3DVector in one book:

struct Vector3D{
float x,y,z;
Vector3D() = default;
Vector3D(float a, float b, float c) : x(a), y(b), z(c) {}
float & operator[](int i){
return ((&x)[i]);
}
};

and if use it as:

    Vector3D myVec(0,2,3);
    std::cout<<myVec[0]<<std::endl;
    std::cout<<myVec[1]<<std::endl;
    std::cout<<myVec[2]<<std::endl;

it will print values of x, y, z

How it works? And Is this safe?

Upvotes: 1

Views: 83

Answers (1)

NathanOliver
NathanOliver

Reputation: 180630

When you do &x you get a pointer to x. When you do pointer[N] what the compiler does is translate that to *(pointer + N). In your code since N is 0 we are left with *(&x) which is just dereferencing the pointer we just created giving back the variable itself.


The code you found this in is actually undefined behavior. When they do

float & operator[](int i){
    return ((&x)[i]);
}

They are assuming there is no padding in the class and treating the 3 separate members as if they were an array. This assumption cannot be made though and the access is explicitly called out as undefined behavior from the standard.

Upvotes: 6

Related Questions