Introduction to the C++20 spaceship operator

CMP
7 min readAug 28, 2023

C++20 introduced the three-way comparison operator, also known as the “spaceship operator” due to its appearance: <=>. The purpose is to streamline the process of comparing objects.

The Basics

Below is a simple example that uses this new spaceship operator:

#include <compare>

int main() {
int a = 1;
int b = 2;

auto result = a <=> b;

if (result < 0) {
std::cout << "a is less than b" << std::endl;
} else if (result == 0) {
std::cout << "a is equal to b" << std::endl;
} else { // result > 0
std::cout << "a is greater than b" << std::endl;
}

return 0;
}

Note that the compare header must be included.

For integral types such as int, the type of the value returned by the spaceship operator is std::strong_ordering, which can have one of three values:

  • std::strong_ordering::less: If the left operand (a) is less than the right operand (b).
  • std::strong_ordering::equal: If a is equal to b.
  • std::strong_ordering::greater: If a is greater than b.

For floating-point types such as double, the spaceship operator returns one of four possible values:

  • std::partial_ordering::less: If a is less than b.
  • std::partial_ordering::equivalent: If a is “equivalent” to b. This is essentially the same as “equal”, but also includes the case of -0 <=> +0.

--

--

CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.