On this page
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
- Evaluated at compile time:
sizeof(expr)never evaluatesexprat runtime;sizeof(arr) / sizeof(arr[0])only works on true arrays (preferstd::size(arr)). - Order struct fields largest-to-smallest to minimize alignment padding.
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
- tuts/cpp/builtins/new_and_delete Linked here; links to this page; shared tags: #builtins, #cpp, #memory, #prog, #tier
- tuts/cpp/builtins/constexpr Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/namespaces Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/c/builtins Linked here; shared tags: #builtins, #prog
- tuts/cpp/builtins/auto shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/classes_and_virtual shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/concepts shared tags: #builtins, #cpp, #prog, #tier