简体   繁体   中英

Is the size_t data type safe to use for str.find()?

I've been looking at code for the find() function for strings, and they store the result of that in a variable with data type size_t. However it is my understanding that size_t is an unsigned int, and if find() does not find the intended string, it returns -1. For example if I have

string s = "asdf";
size_t i = s.find("g")
cout << i;

It gives me 4294967295. However if I replace size_t with the int data type, it gives me -1. The strange thing is when I make a comparison like

string s = "asdf";
size_t i = s.find("g")
if (i == -1) { do_something; }

it works whether i is size_t or int. So which do I use? int or size_t?

Neither.

Under the std::string::find documentation , it recommends that you use string::size_type and string::npos to detect not found in find :

 std::string::size_type i = s.find("g");
 if (i == std::string::npos) std::cout << "Not Found\n";

Live example.

It shouldn't be surprising that int and size_t can be compared with -1 and work, they will have the bits, so when cast to do the comparison they will compare equally, you should however receive a warning such as:

warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

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