Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

alignas — specifying alignment

alignas specifies an alignment requirement for a variable, data member, or class. It accepts a type or an integral constant expression and cannot weaken the natural alignment of the declared object or type.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

alignas(type-id)
alignas(constant-expression)
alignas(pack ...)

Alignment restricts the addresses at which objects may be placed. alignas specifies an alignment requirement, whereas alignof queries it. You can apply alignas to a variable, data member, or class, but not to a function, function parameter, bit-field, or exception declaration in catch.

alignas(T) is equivalent to alignas(alignof(T)). In the numeric form, the argument must be an integral constant expression: 0 has no effect, and a nonzero value must denote a supported alignment. Not every power of two is supported in every context; extended alignments are implementation-dependent.

With multiple specifiers, the strictest nonzero alignment applies. Together they cannot weaken the natural requirement. The form containing ... expands a pack. If any declaration specifies alignment, the definition must specify equivalent alignment; a non-defining declaration may omit it.

The example checks a relationship rather than a platform-dependent byte count. The bytes array remains a byte array: alignment alone does not create a double object. The source is an evolving standard draft, not a frozen C++23 publication.

Examples

#include <iostream>

struct alignas(double) Storage {
    unsigned char bytes[sizeof(double)];
};

static_assert(alignof(Storage) >= alignof(double));

int main() {
    std::cout << std::boolalpha
              << (alignof(Storage) >= alignof(double)) << '\n';
}

Result

true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources