`alignof` — C++ Keyword

`alignof` — C++ Keyword

The alignof keyword in C++: yields the alignment requirement of a type.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

alignof

A compile-time operator that yields the alignment requirement (in bytes) of a type, returned as std::size_t. The result is always a power of two.

Syntax

alignof(type)

Example

#include <print>

struct Packed   { char a; int b; };       // likely padded to 4-byte alignment
struct Aligned  { char a; char b; };      // 1-byte alignment

int main() {
    std::println("alignof(char)  = {}", alignof(char));    // 1
    std::println("alignof(int)   = {}", alignof(int));     // 4
    std::println("alignof(double)= {}", alignof(double));  // 8

    std::println("alignof(Packed)  = {}", alignof(Packed));   // 4
    std::println("alignof(Aligned) = {}", alignof(Aligned));  // 1

    // Manual aligned storage
    alignas(alignof(double)) char buf[sizeof(double)];
    (void)buf;
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}