Course contentsShow
← C
Lesson 572 of 1,2198. Memory ManagementFree lesson

The alignof operator

The alignof operator

What you'll learn: How to use the alignof operator to discover the hardware-imposed memory alignment requirements of any data type.

The Secret Grid of Memory

Think of your computer's RAM not as a continuous blank canvas, but as a sheet of graph paper with specific grid lines. While a single byte can theoretically start anywhere, modern CPUs are much faster at reading data when it sits on specific boundaries—like every 4th or 8th "square" on the grid. This preference is called alignment.

If you try to put an 8-byte piece of data on a boundary that isn't a multiple of 8, the CPU might have to do two memory reads instead of one just to get that single value. To prevent this, C automatically "aligns" your variables to the boundaries the hardware likes best.

Measuring Alignment with alignof

In Phase 1, you learned about sizeof, which tells you how many bytes a type occupies. In C11 and later, we have a sibling operator: alignof. While sizeof tells you the size, alignof tells you the starting rule.

If alignof(int) returns 4, it means the CPU wants every integer to start at a memory address that is a multiple of 4.

To use this in C, you need to include <stdalign.h>.

#include <stdio.h>
#include <stdalign.h>

int main() {
    // Determine the alignment requirements of standard types
    printf("Char alignment: %zu\n", alignof(char));   // Usually 1
    printf("Int alignment:  %zu\n", alignof(int));    // Usually 4
    printf("Double alignment: %zu\n", alignof(double)); // Usually 8

    // You can also check custom structures
    struct MyStruct {
        char a;
        int b;
    };
    
    printf("Struct alignment: %zu\n", alignof(struct MyStruct));
    
    return 0;
}

Why Should You Care?

Most of the time, the compiler handles alignment behind the scenes by inserting "padding" (empty wasted space) between variables to make sure they land on the right grid lines. However, when you start writing high-performance code or sending data directly over a network, knowing these alignment rules is vital.

Using alignof allows you to peek under the hood and see exactly why your structures might be larger than the sum of their parts. It transforms memory from a mystery into a measurable, predictable grid.

Key takeaway

The alignof operator reveals the byte-boundary requirements of a type, helping you understand how the CPU organizes data for maximum speed.