r/programminghumor • • Aug 18 '26

a bit flippant

Post image
1.5k Upvotes

147 comments sorted by

View all comments

Show parent comment

4

u/_yrlf Aug 19 '26 edited Aug 19 '26

That's not true.

Your struct two_bytes is, per the standard, exactly two bytes large (assuming CHAR_BIT == 8, but the return from sizeof will always be 2).

(EDIT: apparently C struct internal padding is not standardized? I'm still searching where the standard defines it. Doesn't a whole lot of code depend on the fact that "C ABI" struct layout is so simple and deterministic?)

(EDIT 2: The ISO C standard allows the compiler to overalign struct members / insert unnecessary padding. But: basically all used platform ABIs for relevant architectures will guarantee that the padding for C structs is minimal according to alignment requirements of the types)

The amount of padding inserted between struct members depends on the natural alignment of the types used, and char is guaranteed to have a size of 1 and an alignment of 1. (EDIT: yes, but the compiler is technically allowed to overalign if the platform ABI doesn't forbid it).

What is true is that it's not guaranteed that adjacent bit fields of the same type will be packed together, and that it's not guaranteed by the standard that char is allowed as a bit field type (unspecified). The standard also guarantees bool and _BitInt(N) are allowed. Also interesting is that the alignment of bit field structs is also unspecified.

In practice, the alignment is that of the underlying type used, and most compilers will combine adjacent bit fields into one as long as the bits fit into the underlying type.

What was truly surprising to me when looking it up though was seeing that the standard allows a bit field declared as int x : 5; to be interpreted as unsigned(!!!). You'd have to explicitly write 'unsigned int' to really mean unsigned.