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);
}
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.
std::cout, then you won't risk guessing types wrong for format specifiers.printfis just wrong. Avoid using it when writing C++. There isstd::cout <<instead and since C++20 alsostd::format. First ask yourself what typeautoinauto ideduces to. You can verify your guess by usingstatic_assert(std::is_same_v<decltype(i), /*guess*/>);.printfin C++ code always ends in tears.