C++ alignas Keyword
Example
Give a structure an alignment of 16 bytes, and print the alignment:
struct alignas(16) MyStruct {
int myNum;
char myLetter;
};
int main() {
cout << alignof(MyStruct);
return 0;
}
Definition and Usage
The alignas keyword specifies the alignment of a variable or type. The alignment is a number of bytes. The data must start at a memory address that is a multiple of this number.
The number must be a power of 2, like 1, 2, 4, 8 or 16. Some hardware works faster, or only works, when data starts at such an address. Most programs do not need alignas, because the compiler chooses a good alignment for each type.
Use the alignof keyword to get the alignment of a type.
Related Pages
Read more about structures in our C++ Structures Tutorial.