Home > Net >  Why is the result value of the compare operation different from the mathematically same formula?
Why is the result value of the compare operation different from the mathematically same formula?

Time:12-15

I'm having trouble comparing size of a vector and simple constant -1

I think both

  • (index >= (arr.size() - 1))
  • ((index 1) >= arr.size())

are logically the same.

However, the first one returns 1 not 0. What's the difference between the two comparisons?

#include <iostream>
#include <vector>

using namespace std;

int main() {
  int index = -1;
  vector<char> arr(6);
  cout << (index >= (arr.size() - 1)) << endl;
  cout << ((index   1) >= arr.size()) << endl;
}

CodePudding user response:

The arr.size method returns an unsigned integer type, so the type of the right-hand side of the comparison is unsigned. This results in the left side being converted to unsigned.

When the value on the left is -1, this gets converted to a very large unsigned number, resulting in the first comparison being true. In the second case, the value on the left is 0 so it doesn't change when being converted to an unsigned type and the comparison is false.

CodePudding user response:

size_t is an unsigned long long. int is a signed type. You are trying to compare an unsigned type with a signed one. The size of the vector will never have the value -1.

  • Related