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:

Formulas

For fixed-width integer and floating-point types, the size follows a simple formula:

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

Further Reading

For complete details, see cppreference: sizeof and cppreference: Fixed-width floating-point types .