Search⌘ K
AI Features

Safely Compare Integers of Different Types

Explore how to safely compare integers of different types using C++20's new integer-safe comparison functions. Understand why direct comparisons between signed and unsigned integers may fail and learn to use functions like cmp_less() for reliable results, enabling you to write more accurate and predictable C++ code.

We'll cover the following...

Comparing different types of integers may not always produce the expected results.

For example:

int x{ -3 };
unsigned y{ 7 };
if(x < y) puts("true");
else puts("false");

We may expect this code to print true, and that's understandable, as 3-3 is less than 77, but here it will print false.

The problem is that x is signed and y ...