Alignment with _Alignas & _Alignof in C
CPUs access multi-byte values fastest (sometimes exclusively) at addresses divisible by their size — this is alignment. The compiler pads structs automatically to satisfy it, _Alignof(int) queries any type's requirement, and _Alignas(16) forces stronger alignment for SIMD types, cache-line separation, or hardware descriptors.
Misaligned access through packed structs or wild casts crashes on strict architectures (ARM) and merely slows x86 — which is why portable code aligns deliberately instead of hoping. C23 spells these alignas/alignof without underscores.
Aligned access is fast (or mandatory)
4-byte ints want 4-divisible addresses — x86 tolerates violations slowly, ARM faults immediately.
Query with _Alignof
_Alignof(double) reports 8 on typical platforms — the requirement, distinct from sizeof's total.
Force with _Alignas
_Alignas(16) float v[4]; guarantees 16-byte start for SSE loads — required by vector intrinsics.
Padding follows alignment
Struct gaps exist to align each member — reordering members largest-first is manual packing for the same rules.
#include <stdio.h>#include <stdalign.h> int main(void) { printf("%zu %zu\n", alignof(int), alignof(double)); _Alignas(16) char buf[16]; printf("%d\n", ((size_t)buf % 16) == 0); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.