Home Ask Login Register

Developers Planet

Your answer is one click away!

Nicky Mirfallah February 2016

find_first_of in c++ gives different values

In the code below, I don't understand why b is false.

string s = "--p--";
cout << s.find_first_of("p") << endl; //prints 2
bool b = s.find_first_of("p")>-1;
cout << b << endl;  //prints 0 (why?)


Bathsheba February 2016

s.find_first_of("p") returns a size_t which is an unsigned type.

The > operator will convert -1 to an unsigned type before s.find_first_of("p")>-1; is evaluated. That's how C++ works: if an operator that takes two arguments encounters a signed and an unsigned type as those arguments, then the signed one gets converted to an unsigned one.

-1 when converted to an unsigned type will be a large positive number. (In fact, it will wrap around to the largest value of size_t.)

So your comparison evaluates to false.

To check if a character is not in a string, use b = s.find_first_of("p") != string::npos;

p0pa February 2016

std::string::find_first_of() return value is of type size_t, and that's typedef for some unsigned type. In order to compare to integer{-1}, compiler should yield a common type. According to the standard usual arithmetic conversions:

If the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.

That means, something like that happens:

bool b = s.find_first_of("p")>static_cast<unsigned>(-1);

You could compile following simple program to observe the behavior.

#include <iostream>

  int i = -1;
  std::cout << static_cast<unsigned>(i);

Post Status

Asked in February 2016
Viewed 1,583 times
Voted 11
Answered 2 times


Leave an answer

Quote of the day: live life