What is align keyword?

  1. what is the use of it.
  2. How it works

Explain with basic example

It’s quite simple really but you need to understand pointers first.
Basically using align allows you to make sure that the pointer to a value is aligned.
For example:

var x: align(4) usize = 0;

test {
    // This is the address in memory of the 'x' variable
    const xAddress = @ptrToInt(&x);
    // As we used align(4), 'x' variable will always be a multiple of 4
    try std.testing.expect(xMemory % 4 == 0);
}

Said like that, alignment is completely useless. One of the only reasons you might want to use the align keyword is when you pass a pointer to a CPU register, and the CPU needs it aligned.
For example, Zig requires you to use align in order to use a custom stack,

var stack: align(std.Target.stack_align) [1024]u8 = undefined;

fn someFunction() void {
}

test {
    @call(.{ .stack = &stack }, someFunction, .{});
}

For even lower level code, it’s also useful for registers like GDTR in x86.

One last use is that sometimes, a CPU can load a value faster if it is aligned, but if you use struct you shouldn’t worry about it as the Zig compiler already handles that for you. But it can still be useful if you use packed struct where you are in complete control of the memory layout.

For more information, you might want to look at the Alignment page on the documentation

5 Likes