-2
string s = "abc";
int i = -1;
cout<<(i < s.length());

It returns false in this case. Why?

But when I write

string s = "abc";
int i = 0;
cout<<(i < s.length());

It returns true

  • 6
    Did you enable compiler warnings? If not, please do so and carefully read the warning message printed for the first snippet. I get `warning: comparison of integer expressions of different signedness: 'int' and 'std::__cxx11::basic_string::size_type' {aka 'long unsigned int'} [-Wsign-compare]` – Botje Jun 02 '22 at 11:50
  • `s.length()` returns an unsigned integer and you are trying to compare it with a signed integer. – Jane Doe Jun 02 '22 at 11:52

1 Answers1

0

The Problem is that you are comparing a int and a size_t, as Botje and Jana Doe pointed out. The solution is as ChrisMM pointed out:

i should be defined as size_t, as opposed to int.

Poder Psittacus
  • 94
  • 1
  • 10
  • Converting `size_t` to `int` is generally a bad idea.... – ChrisMM Jun 02 '22 at 12:07
  • I see your argument, but I also think the solution needs to fit the application. I think this would give problems if the string is longer then 2,147,483,647 characters and that should be well in the range in this case, but if I am wrong please correct me. – Poder Psittacus Jun 02 '22 at 12:14
  • 1
    Generally speaking, you should stick to the signed-ness / type of the function. It's a better habit to be in. `i` should be defined as `size_t`, as opposed to `int`. Firstly, it's unsigned, secondly, `size_t` (and the return type of `length()`) changes based on x86 or x86-64. – ChrisMM Jun 02 '22 at 12:37
  • Ok a well made argument, I will change the answer. – Poder Psittacus Jun 02 '22 at 12:42