Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::default_sentinel_t — range-end marker

std::default_sentinel_t is an empty range-end marker type from <iterator>. It works with iterators that can determine the end themselves, such as std::counted_iterator. It is not a universal replacement for end().

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

Syntax

#include <iterator>

namespace std {
    struct default_sentinel_t { };
    inline constexpr default_sentinel_t default_sentinel{};
}

std::default_sentinel_t, declared in <iterator>, is an empty type representing the end of a range. It stores neither an end address nor an element count. The cooperating iterator must provide the information needed to recognize the end.

Distinguish the type std::default_sentinel_t from the object std::default_sentinel. The latter is declared as inline constexpr default_sentinel_t default_sentinel{};. You can pass the ready-made object or construct a value with std::default_sentinel_t{}. The declarations in the syntax field describe the library; in your program, include the header rather than redeclaring these names in namespace std.

A typical partner is std::counted_iterator: it stores an underlying iterator and a remaining-step count. Comparison with this sentinel reports equality when the count is zero. The sentinel is not an iterator: it is not used for dereferencing or incrementing. Nor does it automatically work with an ordinary pointer or arbitrary container iterator — suitable iterator–sentinel comparison support is required.

In the example, the count 3 limits traversal to the first three array elements, so the expected output is 24 followed by a newline. The count is not a substitute for range validity checks: ensure enough elements are accessible, and do not dereference the iterator after reaching the end.

Examples

#include <iostream>
#include <iterator>

int main() {
    int values[] = {4, 8, 12, 16};
    auto it = std::counted_iterator(values, 3);
    const std::default_sentinel_t end = std::default_sentinel;

    int sum = 0;
    for (; it != end; ++it) {
        sum += *it;
    }
    std::cout << sum << '\n';
}

Result

24

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