...

/

Safe Comparison of Integers

Safe Comparison of Integers

Explore how C++20 ensures the safe comparison of integers.

We'll cover the following...

The comparison of signed and unsigned integers causes unexpected behavior and, therefore, bugs. Thanks to the new safe comparison functions for integers, std::cmp_*, a source of subtle bugs is gone. Additionally, C++20 includes mathematical constants such as e, π, or φ, and with the functions std::midpoint and std::lerp, you can calculate the midpoint of two numbers or their linear interpolation. The new bit manipulation allows you to access and modify individual bits or bit sequences.

When you compare signed and unsigned integers, you may not get the result you expect. Thanks to the six std::cmp_* functions, there is a cure in C++20. To motivate the safe comparison of integers, I want to start with the unsafe variant.

🔑 Integral versus integer

The terms integral and integer are synonyms in C++. This is the wording from the standard for fundamental types: “Types bool, char, char8_t, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types. A synonym for integral type is integer type.” I prefer the term integer in this course.

Unsafe comparison

Run the following program.

Press + to interact
#include <iostream>
int main() {
std::cout << '\n';
std::cout << std::boolalpha;
int x = -3;
unsigned int y = 7;
std::cout<<"-3<7: "<< (x<y) <<'\n';
std::cout << "-3 <= 7: " << (x <= y) << '\n';
std::cout<<"-3>7: "<< (x>y) <<'\n';
std::cout << "-3 => 7: " << (x >= y) << '\n';
std::cout << '\n';
}

Oops! The output does not meet our expectations.

When you read the output of the program, you recognize that 3-3 ...