While debugging a problem, the following issue came up. (Please ignore minor code errors; the code is just for illustration.)
The following struct is defined:
<
C11 will let you define anonymous structure and union members:
typedef union box_t {
unsigned char allBytes[theSizeOfIt];
struct {
uint32_t x;
uint16_t y;
};
} box_t;
That union would behave almost the same as before, you can access .x
etc but the default initialization and assignment would change. If you always ensure that your variables are correctly initialized like this:
box_t real_b = { 0 };
or like this
box_t real_a = { .allBytes = {0}, .x = 1, .y = 2 };
All padding bytes should be correctly initialized to 0
. This wouldn't help if your integer types would have padding bits, but at least the uintXX_t
types that you have chosen will not have them by definition.
gcc and followers implement this already as extension even if they are not yet completely C11.
Edit: In P99 there is a macro to do that in a consistent way:
#define P99_DEFINE_UNION(NAME, ...) \
union NAME { \
uint8_t p00_allbytes[sizeof(union { __VA_ARGS__ })]; \
__VA_ARGS__ \
}
That is the size of the array is determined by declaring an "untagged" union just for its size.