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);
}
4
  • 5
    Use std::cout, then you won't risk guessing types wrong for format specifiers. Commented Apr 5, 2023 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<decltype(i), /*guess*/>);. Commented Apr 5, 2023 at 10:21
  • 1
    Per the first answer: "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." Commented Apr 5, 2023 at 10:25
  • 2
    Using printf in C++ code always ends in tears. Commented Apr 5, 2023 at 11:43

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.