Search code examples
c++comparisonint64uint64

Comparing int64_t and uint64_t


Does anybody know why this code produces such an output? -1 >= 0!!!

[mahmood@tiger ~]$ cat t.cpp
#include <iostream>
#include <stdint.h>
int main()
{
  uint64_t i = 10;
  uint64_t j = 10;
  int64_t k = -1;
  std::cout << "k=" << k << " i-j=" << i-j;
  if (k >= i-j)
    std::cout << " --> yes k>=i-j\n";
  return 0;
}
[mahmood@tiger ~]$ g++ t.cpp
[mahmood@tiger ~]$ ./a.out
k=-1 i-j=0 --> yes k>=i-j
[mahmood@tiger ~]$

I know the types are different and a comparison need two similar types but at the end of the day, it is comparing -1 and 0. Isn't it?


Solution

  • if (k >= i-j)
    

    both sides are converted to unsigned, so perhaps -1 is interpreted as 0xFFFFFFFFFFFFFFFF:

    if (0xFFFFFFFFFFFFFFFF >= 0)
    

    According to the standard (emphasis mine):

    Expressions [expr]

    Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.