I have a situation similar to this one
struct Child
{
u16 x, y;
// other fields
};
struct Father
{
struct Child child1;
struct Child child2;
// other fields
};
Father tilemap[WIDTH][HEIGHT];
Now I just realized I would like to save four bytes for x,y which are set always to the same values for both children of the same father.
All around my code I pass around many Father* and many Child* while recovering coordinates with father->child1->x or child1->x respectively. I would like to safely move the coordinates at Father level but I’m unsure about some facts.
Will the order of declared fields be respected versus any optimization or possible implementation of gcc/g++? Can I be confident that &father == &father.child1?
The real issue here is that I pass Child* without knowing if it’s a child1 or child2 field so I cannot directly know the offset to recover address of father (and coordinates consequently).. I was wondering to use a bit at Child level to distinguish them but will I be easily able to recover address of father then?
Any suggestion would be appreciated, thanks
EDIT: just as a further info, I’m using C++ as my main language but these structs don’t contain ANY strange methods, just fields and empty constructor.
The general rules about field layout in C are:
offsetofof the member field is 0.offsetofof the n-th field is lower than that of the (n+1)-th member.In C++, of course, that is only true if it is a standard layout type, that is roughly, a class or struct with no public/private/protected mixed members, no virtual functions and no members inherited from other classes.