Is it possible to make a union right aligned in C?

Viewed 113

For example,the default alignment of a union is following:

union{
   uint32_t v4;
   __uint128_t v6;
}ip;

//in memory
//aaaa
//bbbbbbbbbbbbbbbb

But I want to have a union right aligned:

//            aaaa
//bbbbbbbbbbbbbbbb

Is it possible to achieve this in C?

2 Answers

You can use a C11 anonymous struct for this.

union {
#pragma pack(1)
    struct {
        char padding_[sizeof(__uint128_t) - sizeof(uint32_t)];
        uint32_t v4;
    };
#pragma pack(0)
    __uint128_t v6;
} ip;

// usage
ip.v4 = 0x7F000000;

You might define

union{
   struct {
     char uselessgap[12];
     uint32_t v4;
   } s;
   __uint128_t v6;
}ip;

Then in your C code use s.v4 instead of v4; and you could even

#define v4 s.v4

I am not sure it is a good idea (that macro).

Another approach would be with your GCC plugin (for a particular version of the GCC compiler) and some __attribute__ handled by it.

Related