Search code examples
c++c++17clangunsignedunsigned-integer

Why `-1 + unsigned(0) > 0` in C++?


The following code output -1 1 in C++.

If i is evaluated as -1, why is it larger than 0?

#include <stdio.h>

int main() {
  auto i = -1 + unsigned(0);
  printf("%d %d\n", i, i > 0);
}

Solution

  • If i is evaluated as -1

    Thats a wrong premise.

    i is not -1. Adding 0u (or unsigned(0)) to -1 results in an unsigned. You may see -1 as output for i because using the wrong format specifier with printf is undefined.

    This

    #include <iostream>
    
    int main() {
      auto i = -1 + unsigned(0);
      std::cout << i << " " << (i>0);
    }
    

    does not rely on guessing the type of i and prints:

    4294967295 1
    

    unsigned(-1) is the largest unsigned integer representable as unsigned.