Look at this simple code:
struct Point {
int x;
int y;
};
void something(int *);
int main() {
Point p{1, 2};
something(&p.x);
return p.y;
}
I expect, that main's return value can be optimized to return 2;, as something doesn't have access to p.y, it only gets a pointer to p.x.
But, none of the major compilers optimize the return value of main to 2. Godbolt.
Is there something in the standard, which allows something to modify p.y, if we only give access to p.x? If yes, does this depend on whether Point has standard layout?
What if I use something(&p.y);, and return p.x; instead?
This is perfectly well-defined:
The
Pointobject (p) and itsxmember are pointer-interconvertible, from [basic.compound]:That
reinterpret_cast<Point*>(x)is valid and does end up with a pointer that points top. Hence, modifying it directly is fine. As you can see, the standard-layout part and the first non-static data member part are significant.Although it's not like the compilers in question optimize out the extra load if you pass a pointer to
p.yin and returnp.xinstead.