Site icon Learn C++

What Is The alignas Alignment Specifier In Modern C++?

What Is The alignas Alignment Specifier In Modern C++

One of the features of Modern C++ is Alignment Support which comes with the C++11 standard. One of the new features of this support is a new keyword alignas which is the alignment specifier. For example, we can apply the alignas alignment specifier to define the minimum block size of data types such as the size of structs. In this post, we explain how we can use alignas in Modern C++ .

What is alignment support in modern C++?

The C++11 standard intends to extend the standard language and library with alignment-related features, known as Alignment Support. These alignment features include:

In this post, we will explain the alignas alignment specifier.

What is the alignment specifier (alignas) in modern C++?

The alignas alignment specifier specifies the alignment requirement of a type or an object.

The syntax of alignas is:

[crayon-6639afe32ff3a903265171/]

Note that, this alignas specifier can be used with:

Is there an alignas alignment specifier example in modern C++?

Here is a simple alignas alignment specifier example used in a struct.

[crayon-6639afe32ff42365388918/]

this means, “align this in multiples of the size of the float type” which is 4 bytes. In other words, whatever you define the size of this struct will be in multiples of float type. That means it will be 4 bytes. If you add more variables or arrays inside, the size of this struct will be in multiples of 4. In other words, 8,12, 16, 64, 128 bytes and so on all word as does 24 bytes, 32bytes etc.

Instead of a float type, you can directly define its size of it with its size. The example below is equivalent to the previous example:

[crayon-6639afe32ff45007315976/]

Is there a full example of how to use the alignas alignment specifier in modern C++?

This full example explains with two different struct examples.

[crayon-6639afe32ff48021739224/]

Here the struct st1 has 2 bytes (x and y) size but its size will be 4 because of alignas(4) specifier. In the second struct st2, we added z[4] bytes. So in total, this st2 struct has 6 bytes size, but again because of alignas(4) it’s size will be in multiples of 4, so the closest next size is 8, it will be 8 bytes.

If you need more in-depth details about this feature, see the original Alignment Support Proposal document.

C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.

Exit mobile version