Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::size_t — the object-size type

std::size_t is an implementation-defined unsigned integer type that can represent the size of any object in bytes. It is the result type of sizeof and is declared by <cstddef>. Do not assume a particular width or use it to represent negative values.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <cstddef>
std::size_t count = 0;

std::size_t names an implementation-defined unsigned integer type large enough to hold the size of any object in bytes. Include <cstddef> when using this name. It is not a distinct class type; do not assume it always means unsigned long or has 64 bits.

The operators sizeof and sizeof... return std::size_t. sizeof reports a size in bytes, not an element count. For an actual array, sizeof(values) / sizeof(values[0]) gives its element count because an array's size is its element count multiplied by its element size. This formula does not work for a pointer: applying sizeof to a pointer measures the pointer itself.

Use std::size_t for nonnegative sizes and appropriate indices, not for values representing a negative difference. Converting -1 to std::size_t produces that type's largest value, not a negative error sentinel. Check the range of signed input before converting it; mixing signed and unsigned types requires care.

The example calculates an array's element count and then sums its elements using a std::size_t index. Its output does not depend on how many bytes an int occupies. The supplied source is an evolving standard draft rather than a frozen C++23 edition; the example is intended for local verification in C++23 mode.

Examples

#include <cstddef>
#include <iostream>

int main() {
    constexpr int values[] = {4, 7, 9};
    constexpr std::size_t count = sizeof(values) / sizeof(values[0]);
    static_assert(count == 3);

    int total = 0;
    for (std::size_t i = 0; i < count; ++i) {
        total += values[i];
    }

    std::cout << "count=" << static_cast<unsigned int>(count) << ", total=" << total << '\n';
}

Result

count=3, total=20

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources