简体   繁体   中英

std::string::npos value is not -1

It's been said in this doc http://www.cplusplus.com/reference/string/string/npos/ that std::string::npos is -1. But when I print out the value, it's not. Is this value architecture dependent?

My test is very simple

std::cout << std::string::npos << std::endl;

which outputs

4294967295

From the link you've given:

This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.

This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.

they say an unsigned integral type

To add to the other answers trying outputting the result of (size_t)-1 . You can verify that this value is the same as std::string::npos .

According to the C++ Standard data member npos of standard class std::basic_string is declared the following way

static const size_type npos = -1;

On the other hand type name size_type corresponds to some unsigned integral type. So what you got is the internal representation of -1 interpreted as unsigned value. This means that the sign bit was considered as a value bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM