Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the result value of the compare operation different for the mathematically same formula in cpp?

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

I think both

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

are logically same.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

#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;
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading