C++20 sections · 1024 units
Open in Course

The npos Constant

Handling failed searches

When find() doesn't locate target, it returns string::npos. This constant represents "not found". Always check for it before using the returned index in other operations. The value of npos is the maximum size_t, large and not a valid index.

Write if (pos != string::npos) to check whether search succeeded. Using unchecked return as index causes bugs. If find returns npos and you pass it to substr, you get unexpected behavior.

Always validate find results first.