I'm trying to work with the offsetof
macro in the following way:
typedef unsigned char u8;
typedef unsigned short u16;
struct MapBlock
{
u16 type : 10;
u8 variant : 3;
bool isTop : 1;
};
struct MapTile
{
struct MapBlock top, middle;
u16 x;
u8 y;
};
MapTile *tfb(struct MapBlock *block)
{
if (block->isTop)
return (MapTile*)block;
else
return (MapTile*)((u8*)block - offsetof(struct MapTile, middle));
}
and it seems to work with this simple test case:
for (int i = 0; i < width; ++i)
for (int j = 0; j < height; ++j)
{
map[i][j].x = i;
map[i][j].y = j;
map[i][j].top.isTop = true;
map[i][j].middle.isTop = false;
}
printf("%p == %p == %p\n",tfb(&map[40][50].top),tfb(&map[40][50].middle),&map[40][50]);
Now the real questions:
- is it safe? (assuming to work with g++)
- will it work with any standard optimization? (mainly
-O2
) - is there a better way to do what I'm doing? (I need to do it to avoid storing x and y for every
MapBlock
but be able to access them through block without knowing relatedMapTile
) - can I avoid the cast to
u8
when subtracting the offset? I guess no but I just wanted to be sure..
Thanks