What is string::npos in C++?

In this article, we will discuss string::npos in C++.

The std::string::npos is a static member constant. It is defined in the string (basic_string.h) header file.

///  Value returned by various member functions when they fail.
static const size_type	npos = static_cast<size_type>(-1);

It is a static member constant with the maximum value representable by the type size_type. The type of size_type is unsigned integer however it is initialized as -1 but due to signed to unsigned implicit conversion, it will hold the largest positive value. This is a portable way to specify the maximum value of any unsigned type.

Let’s print the value of string::npos.

#include <iostream>
using namespace std;

int main() {
	cout<<string::npos<<endl;
	return 0;
}

Output

18446744073709551615

Here 18446744073709551615 is the maximum value of unsigned 64-bit number 264 -1 (on a 64-bit platform).

However,the string::npos generally used in the following cases

  • end of string indicator by functions that expects a string index.
  • error indicator for functions that returns a string index.

Let’s look into these two cases with examples.

Using it as end of string indicator

Firstly we will look into npos as the end of string indicator.

#include <iostream>
using namespace std;
 
int main() {
    string str = "hello";
    string s2(str,3,string::npos); // npos to indicate end of the string
     
    cout<<s2<<"\n";
     
    return 0;
}

Output

lo

Using it as error indicator

In this case, the string::npos is used as the return value from the string find function. If no match found string find function will return string::npos.

#include <iostream>
using namespace std;

int main() {
    string str = "hello";
    
    if(str.find('w') == string::npos)
        cout << "w not found\n";
        
	return 0;
}

Output

w not found

Conclusion

In conclusion, the exact meaning of string::npos depends on the context. Hence, we can summarize as

  • it is maximum value representable by size_type
  • End of string indicator
  • Error indicator

Leave a Comment