0

Let's say we have the following union

union {
        struct {
                unsigned a : 3;
                unsigned b : 10;
                unsigned c : 3;
        } s;
        unsigned i;
} u;

Can you rely on u.i always having the same value if u.s has some value u.s = { .a = A, .b = B, .c = C } or is this implementation defined?

Leander
  • 35
  • 5
  • 1
    You might be interested in **type punning** questions such as [Unions and type-punning](https://stackoverflow.com/questions/25664848/unions-and-type-punning). It has similar questions linked it the "related" panel. – Weather Vane Mar 14 '21 at 17:39
  • 1
    You can't rely on the order of bit-fields across implementations. – Jonathan Leffler Mar 14 '21 at 20:04
  • 1
    Nor can you rely on the value of unspecified bits (say, if `unsigned` is bigger than 16 bits in this example). – mlp Mar 14 '21 at 22:25
  • I guess it requires `sizeof(u.s) == sizeof(unsinged)`. If `u.s` is larger the answer will likely be *no* – tstanisl Mar 14 '21 at 22:37

0 Answers0