Hacker News new | ask | show | jobs
by taminka 159 days ago
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

3 comments

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.

so they're ordered, which i didn't dispute, but alignment is implementation defined, so it could be aligned to the biggest field (like in the article), or packed in whatever (sequential) order the particular platform demands, which was my initial point
Ah, sorry, you're right I forgot about alignment. Yes, alignment is implementation defined, paragraph 16:

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

But, I still don't think that what you've said is true. This is because alignment isn't decided per-object, but per type. That bit is covered more fully in 6.2.8 Alignment of objects.

You also have to be able to take a pointer to a (non-bitfield) member, and those pointers must be aligned. This is also why __attribute__((packed)) and such are non-standard extensions.

Then again: I have not passed the C specification lawyer bar, so it is possible that I am wrong here. I'm just an armchair lawyer. :)

(but for padding, yes, that's correct.)

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.

i was talking abt padding/alignment, not ordering, that's indeed not allowed you're right
> 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.