Learn C
#include "structstypes/alignment.h"

Alignment with _Alignas & _Alignof in C

#concept

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.

#how it works
1

Aligned access is fast (or mandatory)

4-byte ints want 4-divisible addresses — x86 tolerates violations slowly, ARM faults immediately.

2

Query with _Alignof

_Alignof(double) reports 8 on typical platforms — the requirement, distinct from sizeof's total.

3

Force with _Alignas

_Alignas(16) float v[4]; guarantees 16-byte start for SSE loads — required by vector intrinsics.

4

Padding follows alignment

Struct gaps exist to align each member — reordering members largest-first is manual packing for the same rules.

#example
#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;
}
Output
4 8
1
1alignof (stdalign.h's C11 spelling) reports 4 for int and 8 for double here.
2_Alignas(16) forces the buffer onto a 16-byte boundary — the modulo check proves it with 1.
3Requirement queried, guarantee enforced, both verified numerically.
#use cases
SIMD buffers aligned for vector load/store intrinsics
Cache-line separation of hot fields in concurrent structures
Hardware descriptors with mandated alignment in drivers
Packing structs largest-first around known requirements

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.