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 { //…

--

--

CMP

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