c++comparisonstdvectorunsignedsize-t

Why is (-1 < a.size()) false, even though std::vector's size is positive?


Please take a look at this simple program:

#include <iostream>
#include <vector>
 
int main() {
    std::vector<int> a;
    std::cout << "vector size " << a.size() << std::endl;
    
    int b = -1;
    if (b < a.size())
       std::cout << "Less";
    else
       std::cout << "Greater";
}

The program outputs

0
Greater

I am confused by the fact that it outputs Greater despite -1 obviously being less than 0.

I understand that size member function returns an unsigned value, but comparison is still applied to -1 and 0, so what's going on?


Solution

  • Because the size of a vector is an unsigned integral type. You are comparing an unsigned type with a signed one, and the two's complement negative signed integer is being promoted to unsigned. That corresponds to a large unsigned value.

    This code sample shows the same behaviour that you are seeing:

    #include <iostream>
    int main()
    {
      std::cout << std::boolalpha;
      unsigned int a = 0;
      int b = -1;
      std::cout << (b < a) << "\n"; 
    }
    

    output:

    false