logoalt Hacker News

taminkayesterday at 1:12 PM3 repliesview on HN

struct field alignment/padding isn't part of the C spec iirc (at least not in the way mentioned in the article), but it's almost always done that way, which is important for having a stable abi

also, if performance is critical to you, profile stuff and compare outputted assembly, more often than not you'll find that llvm just outputs the same thing in both cases


Replies

steveklabnikyesterday at 1:36 PM

Here's the draft of C23: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf

See "6.7.3.2 Structure and union specifiers", paragraph 16 & 17:

> Each non-bit-field member of a structure or union object is aligned in an implementation-defined manner appropriate to its type.

> Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared.

show 1 reply
cyco130yesterday at 1:35 PM

It is indeed part of the standard. It says "Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared"[1] which doesn't allow implementations to reorder fields, at least according to my understanding.

[1] https://open-std.org/JTC1/SC22/WG14/www/docs/n3220.pdf section 6.7.3.2, paragraph 17.

show 1 reply
ajrossyesterday at 1:30 PM

> struct field alignment/padding isn't part of the C spec iirc

It's part of the ABI spec. It's true that C evolved in an ad hoc way and so the formal rigor got spread around to a bunch of different stakeholders. It's not true that C is a lawless wasteland where all behavior is subject to capricious and random whims, which is an attitude I see a lot in some communities.

People write low level software to deal with memory layout and alignment every day in C, have for fourty years, and aren't stopping any time soon.