C++ is saying that -1 < 13 (in programming) is false

Viewed 91

I have a string called in, a string that has the value of Hello, world!. I also have a integer called i that has the value -1. When I ask C++ to print out if i is less than the length of in (in.length()), it says false but when I try -1 < 15, it says true. Why does it say false? I feel like this is extremely basic math?

1 Answers

string::length() returns an unsigned integer. You can't compare that to a negative signed value, so the -1 gets converted to an unsigned value, which wraps it to a very large number, which is not less than the string's length, hence the result is false.

-1 < 15, on the other hand, is comparing two signed integers, so no conversion is needed, and the result is true, as expected.

Related