Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

alignof — a type's alignment requirement

The alignof operator queries a type's alignment requirement in bytes at compile time. It returns a std::size_t value, not the object's size. For an array it reports the element alignment; for a reference type it reports the alignment of the referenced type.

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

Syntax

alignof(type-id)

alignof(T) reports the alignment requirement of T as a complete-object type. Alignment restricts the addresses at which objects may be placed; a larger value means a stricter requirement. Actual values are implementation-defined—do not assume that alignof(int) is always 4.

The operand must name a complete object type, an array of such elements, or a reference to one of those types. void, function types, and incomplete classes are not allowed. Parentheses are mandatory. Standard C++ accepts a type here, not an expression: for a variable x, use alignof(decltype(x)), not alignof(x).

The result is a prvalue of type std::size_t and an integral constant expression, so it works with constexpr and static_assert. For an array, the result is the element alignment; for a reference, it is the referenced type's alignment. The operator itself needs no header; <cstddef> declares the name std::size_t.

Do not confuse the query alignof(T) with sizeof(T), which reports size, or with alignas(T), which specifies alignment for a declared entity. alignof neither changes alignment nor checks a particular address. The example compares guaranteed relationships instead of printing platform-dependent numbers. The supplied sources are a continuously updated working draft, not a frozen C++23 edition.

Examples

#include <cstddef>
#include <iostream>

int main() {
    constexpr std::size_t alignment = alignof(int);
    static_assert(alignof(int[4]) == alignment);
    static_assert(alignof(int&) == alignment);

    std::cout << std::boolalpha
              << (alignof(int[4]) == alignment) << '\n'
              << (alignof(int&) == alignment) << '\n';
}

Result

true
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