Search⌘ K
AI Features

Iterate Objects of Unknown Length with a Sentinel

Explore how to design a custom iterator with a sentinel to iterate over objects that lack a predetermined length, such as C-strings. Understand the use of a null terminator as a sentinel to signal the end of iteration, enabling you to work with indefinite-length data in range-based loops effectively.

We'll cover the following...

Some objects don’t have a specific length. To know their length, we need to iterate through all their elements. For example, elsewhere in this chapter we’ve seen a generator that doesn’t have a specific length. A more common example would be a C-string.

A C-string is a primitive C-array of characters, terminated with a null '\0' value.

A C-string with its null terminator
A C-string with its null terminator

We use C-strings all the time, even if we don’t realize it. Any literal string in C/C++ is a C-string:

std::string s = "string";

Here, the STL string s is initialized with a literal string. The literal string is a C-string. If we look at the individual characters in hexadecimal, we’ll see the null terminator:

for (char c : "string") {
std::cout << format("{:02x} ", c);
}

The word “string” has six ...