0

In the test

bool test = -1 > vec.size(); 

where vec is a non-empty vector, the value of test is true. Why? How would this be investigated?

  bool test0 = -1 > 10; // false
  // vec.size() = 10
  bool test1 = -1 > vec.size();  // true
  bool test2 = 0 > vec.size();   // false
  bool test3 = 1 > vec.size();   // false
  bool test4 = 11 >= vec.size(); // true
J4SON
  • 11
  • 4
  • 1
    `size()` returns an unsigned integer. You can't compare signed and unsigned integers directly. `-1` is being implicitly converted to an unsigned integer type, which can't represent the value `-1` correctly. – François Andrieux Nov 07 '22 at 14:39
  • 1
    *How would this be investigated?* This particular issue is easily caught if you enable your compiler warnings. – Yksisarvinen Nov 07 '22 at 14:40
  • fwiw, since C++20 there is [`std::ssize`](https://en.cppreference.com/w/cpp/iterator/size) (non-member) which returns a signed value – 463035818_is_not_an_ai Nov 07 '22 at 14:45

0 Answers0