In many cases I find that I would like to have access to raw data in union but I dont want to calculate the size or I want to keep it flexible.
For example (a bit artificial, but I hope it conveys the idea), I dont want to adjust the size of raw if I change how othertype_t looks like:
#pragma pack(push, 1)
typedef union {
uint8_t raw[0];
struct {
uint8_t bar[32];
othertype_t foo[4];
};
} sometype_t;
#pragma pack(pop)
Later I can do things like sizeof(union sometype_t)
to know the size of raw
.
Using raw[0] works but I know that is a gcc non-standard extension. How can I do this in a more portable way?
As a 'trick', I could do something like raw[1]
but it feels a bit misleading.
Update: Someone indicated that this is undefined behavior in C++. Could you include some additional information about this?