Alignas in C++ 11 (original) (raw)
Last Updated : 9 Jun, 2026
The alignas specifier was introduced in C++11 to provide custom memory alignment for variables and user-defined types such as classes and structures. Proper alignment can improve memory access efficiency and help optimize performance on modern hardware architectures.
- Can be applied to variables, classes, structs, unions, and enum declarations
- Helps optimize memory layout and CPU access performance
Syntax
alignas( alignment_value )
where, alignment_value is an integral constant expression that specifies the desired alignment in bytes.
Applicability of alignas
The alignas specifier can be applied to:
- Declarations or definitions of a class, struct, union, or enum
- Non-bit-field data members of a class or struct
- Variable declarations (except function parameters and exception parameters in catch blocks)
**Note: The examples below use the alignof operator to determine the alignment requirement of a type. Familiarity with alignof will help in understanding the output.
C++ `
#include using namespace std;
// struct is aligned to 16 bytes in memory. struct alignas(16) Demo {
int var1l; // 4 bytes
int var2; // 4 bytes
short s; // 2 bytes
// char aligned to 4 bytes in memory.
alignas(4) char arr[5];};
// driver code int main() { cout << alignof(Demo) << endl; // output: 16 return 0; }
`
**Explanation
- The Demo structure is declared with alignas(16), so its objects are aligned on 16-byte boundaries.
- The array arr uses alignas(4), giving it a 4-byte alignment requirement.
- The compiler chooses the largest alignment requirement among the structure and its members.
- Therefore, alignof(Demo) returns 16.
**Practice: Try to use sizeof(Demo) and compare it with alignof(Demo) and check the difference if any.
Real-Time Use Cases of alignas
The alignas specifier is commonly used in performance-critical applications where memory alignment affects efficiency.
- To reduce cache-line contention in multi-threaded programs
- To improve memory access performance and CPU efficiency
- To implement custom memory layouts for low-level systems programming