0

I have a string called in, a string that has the value of "Hello, World!". I also have an 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 arithmetic.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ceyhun
  • 39
  • 7
  • 7
    You should read [Signed/unsigned comparisons](https://stackoverflow.com/q/5416414/555045) – harold Sep 09 '22 at 23:27
  • Some related questions: [Weird std::string::size() in a for loop](https://stackoverflow.com/questions/37090091/) -- [sizeof() operator in if-statement](https://stackoverflow.com/questions/17293749/) -- [Why does my program skip the while loop? 2 is bigger than -1](https://stackoverflow.com/questions/57775122/) -- [c++ vector size. why -1 is greater than zero](https://stackoverflow.com/questions/16250058/) – JaMiT Sep 10 '22 at 01:21

1 Answers1

9

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • This is very interesting! I did not know of this. How can I make it so that it returns a signed integer? – Ceyhun Sep 09 '22 at 23:30
  • "*How can I make it so that it returns a signed integer?*" - You can't change the **type** it returns. But you can *typecast* the **value** it returns, eg: `static_cast(in.length())` – Remy Lebeau Sep 09 '22 at 23:31
  • @Ceyhun that would require a language change proposal. And it would be unlikely to pass the committee. You can however cast the return value to a signed number. – Taekahn Sep 09 '22 at 23:31
  • That was what I was asking for - Thank you! I will accept this answer when I can. – Ceyhun Sep 09 '22 at 23:32
  • 2
    @Ceyhun You can use `std::ssize(in)` to get the "signed size". Or you can use [`std::cmp_less(-1, in.size())`](https://en.cppreference.com/w/cpp/utility/intcmp) to do the comparison without conversion to unsigned. But you really should just turn on your compiler warning for signed/unsigned comparison. – Artyer Sep 09 '22 at 23:40