C Bit-Field Pitfalls

(os2museum.com)

20 points | by fanf2 3 hours ago ago

3 comments

  • pjmlp 2 hours ago

    It is much safer to pack/unpack bits manually than trusting bitfields will work as expected.

  • fsckboy an hour ago

    >The troublesome behavior is demonstrated by the lines performing the left shift. We take a 12-bit wide bit-field, shift it left by 20 bits so ...

    this is nonsense. I don't know what they expect would happen, but who cares? I wouldn't shift a 12 bit field by more than ±11 bits.

    you can shift the "enclosing" word of memory if you want, just put the original definition in a union.

  • mwkaufma 2 hours ago

    tl;dr standard is unclear if they should respect the signed-ness of the declaration (MSCV), or always promote to int before converting to a receiving type (GCC, Clang).

    I suppose you could say MS's choice reflects a commitment to backwards compatibility, whereas GCC/Clang is always chomping at the bit to introduce more aggressive optimizations that signed-integer-undefined-behavior affords?