0

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);
}
Max
  • 414
  • 1
  • 4
  • 12
  • 5
    Use `std::cout`, then you won't risk guessing types wrong for format specifiers. – StoryTeller - Unslander Monica Apr 05 '23 at 10:18
  • 3
    "_If i is evaluated as -1_": It is not. Your `printf` is just wrong. Avoid using it when writing C++. There is `std::cout <<` instead and since C++20 also `std::format`. First ask yourself what type `auto` in `auto i` deduces to. You can verify your guess by using `static_assert(std::is_same_v);`. – user17732522 Apr 05 '23 at 10:21
  • 1
    Per the [first answer](https://stackoverflow.com/a/50632): _"In your case, we have one unsigned int and signed int. Referring to (3) above, since both operands have the same rank, [...] will need to be converted an unsigned integer."_ – E_net4 Apr 05 '23 at 10:25
  • 2
    Using `printf` in C++ code always ends in tears. – Sam Varshavchik Apr 05 '23 at 11:43

1 Answers1

3

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185