In a library for binary messaging, I have some structs like these:
struct __attribute__((__packed__)) Header {
int16_t msg_type;
int16_t msg_size;
char payload[];
};
struct __attribute__((__packed__)) SomeMessage {
static const int value MsgType = 42;
int64_t field1;
int32_t field2;
// ...
};
For writing the messages, I can make a packed type containing the two:
struct __attribute__((__packed__)) WriteMessage {
Header hdr;
SomeMessage body;
};
And this works - the size of the type and the alignments of all the fields is as I would want it to be. GCC gives me a warning, but otherwise works:
warning: ISO C++ forbids zero-size array ‘payload’ [-pedantic]
But why does it work? Effectively, char payload[]
took zero space - isn't that disallowed? Am I relying on undefined behavior that happens to do something sensible?