Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The alignof operator is a compile-time unary operator that returns the alignment requirement of a specified type in bytes. It evaluates to a constant expression of type std::size_t, representing the number of bytes between successive memory addresses at which objects of the queried type can be allocated.
alignof(type-id)

Evaluation Rules and Mechanics

The behavior of alignof depends strictly on the category of the type-id provided as its operand:
  • Fundamental Types: Returns the architecture-specific alignment boundary required by the hardware (e.g., typically 4 for int and 8 for double on 64-bit systems).
  • Class/Struct Types: Returns the strictest (largest) alignment requirement among all its base classes and non-static data members. The alignment requirements of these subobjects dictate where the compiler must insert padding, but padding itself consists of empty space and does not factor into the alignof evaluation. The alignment value can also be explicitly overridden using the alignas specifier.
  • Array Types: Returns the alignment requirement of the underlying element type, not the alignment or size of the entire array block.
  • Reference Types: Returns the alignment requirement of the referenced type. The reference itself does not have a distinct alignment queried by this operator.

Type Constraints

The type-id passed to alignof must be a complete type, an array type, or a reference type. Applying alignof to an incomplete type, a function type, or the void type is a constraint violation. This renders the program ill-formed and results in a standard compilation error, as the compiler cannot determine the alignment for these types.

Syntax Visualization

#include <iostream>
#include <cstddef>

struct Base {
    double d;    // alignof(double) == 8
};

struct Derived : Base {
    char c;      // alignof(char) == 1
    int i;       // alignof(int) == 4
};

struct alignas(32) OveralignedStruct {
    int i;
};

int main() {
    // Evaluates to the architecture's default alignment for int
    constexpr std::size_t int_align = alignof(int); 

    // Evaluates to 8, driven by the strictest requirement from the Base class
    constexpr std::size_t struct_align = alignof(Derived); 

    // Evaluates to 32, driven by the alignas specifier
    constexpr std::size_t custom_align = alignof(OveralignedStruct); 

    // Evaluates to alignof(int), ignoring the array bounds
    constexpr std::size_t array_align = alignof(int[100]); 

    // Evaluates to alignof(double), ignoring the reference semantics
    constexpr std::size_t ref_align = alignof(double&); 

    return 0;
}
Because alignof resolves entirely during compilation, its result is guaranteed to be a core constant expression.
Master C++ with Deep Grasping Methodology!Learn More