Safe Integer Comparisons C++20
From C++ Weekly - Ep 284
1. Requirements
Required C++20
2. Problem
Never compare two values from different types.
#include <iostream> int getval() { return -1; }; unsigned int getval2() { return 1; }; int main(int argc, char *argv[]) { std::cout << getval() << " < " << getval2() << " = " << std::boolalpha << (getval() < getval2()) << std::endl; return 0; }
Output:
-1 < 1 = false
No default warning
Due to -1 being 1111…111 in C2 and 1 just 0000…1
3. Solution
C++20
#include <iostream> #include <utility> // <-- int getval() { return -1; }; unsigned int getval2() { return 1; }; int main(int argc, char *argv[]) { std::cout << getval() << " < " << getval2() << " = " << std::boolalpha << std::cmp_less(getval(), getval2()) << std::endl; return 0; }
Output:
-1 < 1 = true