Alignment: The .alignof Property

Understand the working of the .alignof property.

We'll cover the following

By default, every object is placed at memory locations that are multiples of an amount specific to the type of that object. That amount is called the alignment of that type. For example, the alignment of int is 4 because int variables are placed at memory locations that are multiples of 4 (4, 8, 12, etc.).

Alignment is needed for CPU performance or requirements because accessing misaligned memory addresses can be slower or cause a bus error. In addition, certain types of variables only work properly at aligned addresses.

The .alignof property

The .alignof property of a type is its default alignment value. For classes, .alignof is the alignment of the class variable, not the class object. The alignment of a class object is obtained by std.traits.classInstanceAlignment.

The following program prints the alignments of various types:

Get hands-on with 1000+ tech skills courses.