On this page
  1. sizeof & alignof
  2. Overview
  3. Notes & Pitfalls
  4. Example

sizeof & alignof

Prev: Namespaces | Up: builtins | Next: new & delete
Rel: C Built-ins, constexpr & consteval
Ref: cppreference — sizeof | cppreference — alignof
Tags: #public #prog #cpp #builtins #memory #tier/standard


Overview

sizeof returns the size in bytes of a type or expression at compile time (std::size_t), and alignof returns its required memory alignment in bytes. alignas(N) lets you over-align structs or buffers (for example, to 64-byte cache lines to prevent false sharing).

Notes & Pitfalls

Example

#include <cassert>
#include <cstdint>

struct Packed { std::uint64_t a; std::uint32_t b; std::uint8_t c; };

int main() {
    static_assert(alignof(Packed) == alignof(std::uint64_t));
    assert(sizeof(Packed) >= 13);
}

Linked from

Related notes