Ch2.7: sizeof
What is sizeof?
The sizeof operator in C++ returns the size of a type or object in bytes.
Its result type is always ::std::size_t, an unsigned integer type guaranteed to hold any object size.
For fundamental types, sizeof is evaluated at compile time and is a constant expression.
Basic Examples
#include <fast_io.h>
#include <cstddef>
#include <cstdint>
#include <cstdfloat>
int main()
{
using namespace ::fast_io::iomnp;
::std::size_t sz1 = sizeof(::std::size_t);
::std::size_t sz2 = sizeof(::std::int32_t);
::std::size_t sz3 = sizeof(double);
::std::size_t sz4 = sizeof(::std::float64_t);
::std::size_t sz5 = sizeof(::std::float32_t);
::std::size_t sz6 = sizeof(::std::bfloat_t);
println("sizeof(::std::size_t) = ", sz1); // equals architecture byte size (8 on 64-bit, 4 on 32-bit)
println("sizeof(::std::int32_t) = ", sz2); // formula: 32/8 = 4
println("sizeof(double) = ", sz3); // typically 8
println("sizeof(::std::float64_t) = ", sz4); // 64/8 = 8
println("sizeof(::std::float32_t) = ", sz5); // 32/8 = 4
println("sizeof(::std::bfloat_t) = ", sz6); // 16/8 = 2
}
Key takeaway: The result of sizeof is always a ::std::size_t value.
On typical 64‑bit systems:
sizeof(::std::size_t)= 8 bytes (architecture word size)sizeof(::std::int32_t)= 32/8 = 4 bytessizeof(double)= 8 bytessizeof(::std::float64_t)= 64/8 = 8 bytessizeof(::std::float32_t)= 32/8 = 4 bytessizeof(::std::bfloat_t)= 16/8 = 2 bytes
Formulas
For fixed-width integer and floating-point types, the size follows a simple formula:
sizeof(::std::intXX_t)= XX / 8sizeof(::std::float32_t)= 32 / 8 = 4sizeof(::std::float64_t)= 64 / 8 = 8sizeof(::std::bfloat_t)= 16 / 8 = 2
For ::std::size_t, the size equals the architecture’s byte size:
4 bytes on 32‑bit systems, 8 bytes on 64‑bit systems.
Operator Characteristics
sizeofis evaluated at compile time for fundamental types.- It does not evaluate its operand — no runtime side effects.
- Result type is always
::std::size_t. - Parentheses are required when applied to a type, optional for objects.
Further Reading
For complete details, see cppreference: sizeof and cppreference: Fixed-width floating-point types .