Andrey Chernukha
Andrey Chernukha

Reputation: 21808

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?

Upvotes: 7

Views: 4294

Answers (3)

juanchopanza
juanchopanza

Reputation: 227498

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

Upvotes: 11

user529758
user529758

Reputation:

The signature for vector::size() is:

size_type size() const noexcept;

size_type is an unsigned integral type. When comparing an unsigned and a signed integer, the signed one is promoted to unsigned. Here, -1 is negative so it rolls over, effectively yielding the maximal representable value of the size_type type. Hence it will compare as greater than zero.

Upvotes: 4

Jesus Ramos
Jesus Ramos

Reputation: 23266

-1 unsigned is a higher value than zero because the high bit is set to indicate that it's negative but unsigned comparison uses this bit to expand the range of representable numbers so it's no longer used as a sign bit. The comparison is done as (unsigned int)-1 < 0 which is false.

Upvotes: 2

Related Questions