-2

I'm trying to compare the following two quantities: an integer 'i' and the size of a vector v.

#include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector <int> v(26,0);
    int i = -1;

    cout << i << " " << v.size() << endl;
    if (i < v.size()) cout << "a1" << endl;
    else cout << "b1" << endl;

    if (-1 < 26) cout << "a2" << endl;
    else cout << "b2" << endl;
    return 0;
}

When I run the following code, the output that I get is: -1 26 b1 a2

whereas I expect it to give: -1 26 a1 a2

Why is this happening?

Evil_Transistor
  • 188
  • 1
  • 1
  • 10
  • 1
    When comparing signed to unsigned the compiler converts the signed value to unsigned. That's why you see what you see. The unsigned version of `-1` is just the biggest unsigned integer. – freakish Mar 31 '19 at 17:58
  • 1
    Is your compiler warning you about comparing a signed value to an unsigned value? If no, you need a better C++ compiler. If yes, don't ignore your compiler's warning messages. There's always a reason for them. – Sam Varshavchik Mar 31 '19 at 17:58
  • @SamVarshavchik No, the compiler didn't give me any warnings. – Evil_Transistor Mar 31 '19 at 18:02
  • 1
    `gcc`, with the `-Wall` option (after all, all experienced C++ developers automatically enable all compiler warnings), definitely gives a warnings message. – Sam Varshavchik Mar 31 '19 at 18:04
  • 1
    `-Wall` is not "all compiler warnings". It is more like `-Wsome`. I recommend `-Wall -Wextra -pedantic` – Lightness Races in Orbit Mar 31 '19 at 18:16

1 Answers1

1

The two arguments for i < v.size() are int (which is signed) and size_t (which is unsigned). In this case C++ rules say that the signed quantity is converted to unsigned first. So -1 is converted to an unsigned quantity. This is done by adding the unsigned range to the number in question. In the case of -1 this results in the largest possible unsigned quantity, which is bigger than whatever v.size() is so that comaprison is false.

I'm sure you know why -1 < 26 is true.

Try not to mix signed and unsigned types when comparing integers. It can lead to surprises. Your compiler should warn you about this.

john
  • 85,011
  • 4
  • 57
  • 81