</>EmbeddedInterview

How do you find the alignment of a variable or type?

Easy"Coding: Memory & String Functions"
#include <stdalign.h>
#include <stdint.h>
#include <stdio.h>

struct s { char c; double d; };

int main(void)
{
    printf("alignof(double)   = %zu\n", alignof(double));      /* 8 on most ABIs */
    printf("alignof(struct s) = %zu\n", alignof(struct s));
    double x;
    uintptr_t a = (uintptr_t)&x;
    printf("address alignment = %zu\n", (size_t)(a & -a));      /* largest power of two dividing the address */
    printf("is 16-aligned: %d\n", (a & 15u) == 0);
    return 0;
}

Points: alignof/_Alignof gives the type's requirement (compile time); addr & -addr gives the largest power of two that divides an actual address; addr % n == 0 (or (addr & (n−1)) == 0 for powers of two) checks a specific alignment. Without C11: offsetof(struct { char c; T t; }, t). Increase alignment with _Alignas(32)/alignas(32) or __attribute__((aligned(32))).