...

/

Iterate Objects of Unknown Length with a Sentinel

Iterate Objects of Unknown Length with a Sentinel

Learn to iterate objects of unknown length with a sentinel.

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.

Press + to interact
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 ...