# Three-way comparison

> C++20 lets one operator<=> answer less, equal or greater, and lets the compiler rewrite the other relational operators in terms of it. Equality stays separate, and the rewriting rules for == changed the meaning of some existing code.

- **Source:** C++ Atlas (https://cppatlas.com/topics/three-way-comparison)
- **Track:** Expressions and functions
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [expr.spaceship] (https://eel.is/c++draft/expr.spaceship), [cmp.categories] (https://eel.is/c++draft/cmp.categories), [class.compare.default] (https://eel.is/c++draft/class.compare.default), [class.eq] (https://eel.is/c++draft/class.eq), [class.spaceship] (https://eel.is/c++draft/class.spaceship), [over.match.oper] (https://eel.is/c++draft/over.match.oper), [over.match.best] (https://eel.is/c++draft/over.match.best), [comparisons.three.way] (https://eel.is/c++draft/comparisons.three.way)
- **cppreference links:** [Default comparisons](https://en.cppreference.com/w/cpp/language/default_comparisons), [Comparison operators](https://en.cppreference.com/w/cpp/language/operator_comparison), [std::strong_ordering](https://en.cppreference.com/w/cpp/utility/compare/strong_ordering), [std::partial_ordering](https://en.cppreference.com/w/cpp/utility/compare/partial_ordering), [std::compare_three_way](https://en.cppreference.com/w/cpp/utility/compare/compare_three_way)
- **Prerequisites:** operator-overloading, overload-resolution

## The one idea

Before C++20, a fully comparable type needed six operators, and they could disagree with each other. C++20 splits the job in two. **Ordering** is answered by one function, `operator<=>`, which returns a value saying less, equivalent, greater, or, for some types, unordered. **Equality** is answered by `operator==`. The compiler then rewrites `<`, `<=`, `>` and `>=` in terms of `<=>`, and `!=` in terms of `==`, and it is also allowed to swap the operands.

The two halves are deliberately independent. Writing `<=>` by hand does not give you `==`, because equality can often be answered far more cheaply than ordering: two strings of different lengths are unequal without looking at a single character.

> **Mental model.** You write at most two functions, `==` and `<=>`. The compiler derives the other four operators, and it tries each comparison with the operands in both orders.

## Comparison categories

The result of `<=>` is one of three class types from `<compare>`, and the type itself documents what kind of order you have.

| Category | Values | Meaning of "equivalent" |
|---|---|---|
| `std::strong_ordering` | `less`, `equal`, `greater` | interchangeable values |
| `std::weak_ordering` | `less`, `equivalent`, `greater` | same rank, possibly distinguishable |
| `std::partial_ordering` | `less`, `equivalent`, `greater`, `unordered` | some pairs cannot be compared |

A case-insensitive string comparison is a weak ordering: `"Abc"` and `"abc"` are equivalent but not identical. Floating-point numbers are partially ordered, because a NaN is neither less than, equal to, nor greater than anything, including itself.

Conversions only go towards weaker guarantees. A `strong_ordering` converts implicitly to `weak_ordering` and to `partial_ordering`, and a `weak_ordering` converts to `partial_ordering`. Nothing converts the other way, because that would invent a guarantee.

You use a result by comparing it with the literal `0`: `r < 0` means less, `r == 0` means equal or equivalent. The standard says comparing a category value with anything other than a literal zero is undefined behaviour; library implementations make the parameter a type that only a literal `0` converts to, so `r == 1` is rejected in practice. The named functions `std::is_lt`, `std::is_eq` and friends say the same thing in words.

```cpp
#include <compare>
#include <cmath>

void demo() {
  double nan = std::nan("");
  auto r = nan <=> 1.0;            // std::partial_ordering::unordered
  bool all_false = !(r < 0) && !(r == 0) && !(r > 0);   // true
  (void)all_false;
}
```

## The built-in `<=>`

For integers, enumerations and pointers, the built-in `<=>` yields `std::strong_ordering`. For floating-point operands it yields `std::partial_ordering`. Arithmetic operands go through the usual arithmetic conversions first, but with a twist that makes `<=>` stricter than `<`: if the conversion would be narrowing, other than integer to floating point, the program is ill-formed.

```cpp
#include <compare>

bool old_way = -1 < 1u;              // compiles: -1 becomes a huge unsigned, so false
// auto new_way = -1 <=> 1u;         // ill-formed: int to unsigned is narrowing
```

When the narrowing operand is a variable rather than a constant, Clang rejects it but GCC only warns by default and needs `-pedantic-errors` to reject it, so do not use GCC's acceptance as evidence. For pointers, the built-in comparison has an unspecified result for pointers into unrelated objects, just as `<` does.

## Defaulted `<=>` and `==`

`= default` asks the compiler to compare memberwise. A defaulted `operator==` compares base subobjects in declaration order, then non-static data members in declaration order, and stops at the first inequality. A defaulted `operator<=>` does the same with `<=>`, returning the first result that is not equal.

If you declare `auto operator<=>(const T&) const = default;` and do not declare any `operator==`, the compiler also declares a defaulted `operator==` for you. That is the only way `==` comes from `<=>`, and it is still memberwise `==`, not a call to `<=>`.

```cpp
#include <compare>

struct Version {
  int major, minor, patch;
  auto operator<=>(const Version&) const = default;   // also declares == = default
};

static_assert(Version{1, 2, 3} < Version{1, 3, 0});
static_assert(Version{1, 2, 3} == Version{1, 2, 3});
```

With an `auto` return type, the result is the common comparison category of all the member comparisons: one `double` member makes the whole thing `std::partial_ordering`. If some member has no usable `<=>`, the defaulted `operator<=>` with `auto` is defined as deleted.

If you name the return type instead, the compiler is allowed to fall back on `==` and `<` for members that lack `<=>`. [class.spaceship] calls this the synthesized three-way comparison: it uses `<=>` when available and otherwise builds the requested category from `a == b` and `a < b`. That is how a C++20 type can wrap a pre-C++20 type that only has `<` and `==`.

```cpp
#include <compare>

struct Legacy {
  int v;
  bool operator<(const Legacy& o) const { return v < o.v; }
  bool operator==(const Legacy& o) const { return v == o.v; }
};

struct Bad  { Legacy l; auto operator<=>(const Bad&) const = default; };   // deleted
struct Good { Legacy l; std::weak_ordering operator<=>(const Good&) const = default; };
```

A defaulted comparison is also deleted when the class has a reference member or is a union-like class, since there is no obvious meaning to compare.

> **Pitfall.** A hand-written `operator<=>` gives you `<`, `<=`, `>` and `>=` but not `==` or `!=`. Add `bool operator==(const T&) const = default;` or write `==` yourself.

## Rewritten and reversed candidates

For a relational expression `a < b`, overload resolution considers, in addition to every `operator<`, the rewritten candidates `(a <=> b) < 0` and, reversed, `0 < (b <=> a)`. For `a != b` it considers `!(a == b)` and `!(b == a)`. For `a == b` it adds the reversed `b == a`. This is why one member `operator==(int) const` makes both `s == 42` and `42 == s` work.

```cpp
#include <compare>

struct Id {
  int v;
  constexpr bool operator==(int x) const { return v == x; }
  constexpr std::strong_ordering operator<=>(int x) const { return v <=> x; }
};

static_assert(42 == Id{42});    // reversed: Id{42} == 42
static_assert(42 >  Id{7});     // rewritten: 0 > (Id{7} <=> 42)
static_assert(Id{1} != 2);      // rewritten: !(Id{1} == 2)
```

When a rewritten or reversed candidate ties with an ordinary one on conversions, [over.match.best] prefers the ordinary candidate, and prefers a non-reversed rewrite over a reversed one. A rewritten `!=` or reversed `==` must return `bool`; if the selected `operator==` returns something else, the program is ill-formed.

> **Standardese.** [over.match.oper] defines the rewritten candidates. For `x < y` and the other relational operators they are the `operator<=>` functions, tried as `x <=> y` and reversed as `y <=> x`. For `x != y` they are the `operator==` functions, tried both ways round. For `x == y` they are the reversed `y == x`, and for `x <=> y` the reversed `y <=> x`, used as `0 <=> (y <=> x)`.

## What C++20 broke

Reversed candidates are added silently to code written before C++20, and some of that code changed meaning. The classic case is a member `operator==` that forgot `const`:

```cpp
struct S {
  int v;
  bool operator==(const S& o) { return v == o.v; }   // not const
};

bool same(S a, S b) { return a == b; }
```

For `a == b`, the ordinary candidate binds `a` to the non-const object parameter exactly and `b` to `const S&`. The reversed candidate does the opposite. Each is better for one argument, so by the C++20 rules the call is ambiguous. GCC and Clang accept it with a warning and pick the ordinary candidate; the fix is to make the operator `const`.

P2468, adopted for C++23 and applied by compilers as a defect report against C++20, added an escape hatch for code like this: if a matching `operator!=` is declared in the same scope as an `operator==`, that `operator==` is not used for reversed or rewritten candidates. A pre-C++20 class that defines both operators keeps its old behaviour.

## Library support

`std::compare_three_way` is a function object whose call operator computes `a <=> b`, constrained on the `std::three_way_comparable_with` concept. For pointers it gives an implementation-defined strict total order even where the built-in `<=>` is unspecified, which is what you want as a container key.

The library also has an exposition-only helper, *synth-three-way*, used to define `<=>` for `std::pair`, `std::tuple`, `std::array` and the other containers. It calls `<=>` when the element type has one and otherwise falls back to `<`, producing `std::weak_ordering`. So a `std::pair<Legacy, int>` supports `<=>` even though `Legacy` does not. This is related to, but not the same as, the core language's synthesized three-way comparison, which only applies when a defaulted `<=>` names its return type.

For floating point, `std::strong_order` provides the IEEE total order in which every NaN has a place, and `std::weak_order` and `std::partial_order` give the corresponding weaker orders. What a comparator must satisfy to be used by sorting algorithms is the subject of strict-weak-ordering-and-comparators.

## What to remember

- `<=>` answers ordering, `==` answers equality; the compiler rewrites `<`, `<=`, `>`, `>=` from the first and `!=` from the second.
- `strong_ordering` converts to `weak_ordering` converts to `partial_ordering`, never backwards.
- Compare a category value only with literal `0`, or use `std::is_lt` and friends.
- Built-in `<=>` on floating point is `partial_ordering`; NaN gives `unordered`, and every relational test is false.
- `-1 <=> 1u` is ill-formed because the conversion narrows, even though `-1 < 1u` compiles.
- A hand-written `<=>` does not provide `==`; only a defaulted `<=>` implicitly declares a defaulted `==`.
- Defaulted `<=>` with `auto` is deleted if a member lacks `<=>`; naming the return type lets it fall back on `==` and `<`.
- Reversed candidates make `42 == s` work, and can make non-const member `operator==` ambiguous.
- A matching `operator!=` suppresses rewriting for that `operator==` (P2468).

## Concept Map Outline

- **Three-way comparison:** operator<=> answers ordering, operator== answers equality, and the compiler rewrites the rest.
  - **Comparison categories:** The result type of <=> says what kind of order the type has.
    - **strong_ordering:** Equal values are interchangeable; built-in for integers, enums and pointers.
    - **weak_ordering:** Equivalent values may still be distinguishable, as in case-insensitive strings.
    - **partial_ordering:** Adds unordered; built-in <=> on floating point returns it, and NaN is unordered.
    - **One-way conversions:** strong converts to weak converts to partial, never the other way.
    - **Compare with literal 0:** Test results as r < 0 or r == 0; comparing with any other value is undefined.
  - **Built-in <=>:** Applies the usual arithmetic conversions, but more strictly than <.
    - **No narrowing:** -1 <=> 1u is ill-formed because int to unsigned narrows.
    - **Unrelated pointers:** Comparing pointers into unrelated objects gives an unspecified result.
  - **Defaulting:** = default compares bases, then members, in declaration order.
    - **Implicit ==:** A defaulted <=> declares a defaulted == only if no operator== is declared.
    - **auto return type:** Deduces the common category; deleted if any member lacks <=>.
    - **Named return type:** Lets the compiler synthesize the result from == and < for legacy members.
    - **Deleted cases:** Reference members and union-like classes make defaulted comparisons deleted.
  - **Rewritten candidates:** Overload resolution adds rewritten and reversed forms for comparisons.
    - **Relational:** a < b also tries (a <=> b) < 0 and 0 < (b <=> a).
    - **Equality:** a != b tries !(a == b) and !(b == a); a == b tries b == a.
    - **Tie-breakers:** Ordinary candidates beat rewritten ones, and non-reversed beat reversed.
    - **bool required:** A rewritten == chosen for != or reversed == must return bool.
  - **C++20 breakage:** Reversed candidates appeared in old code without warning.
    - **Non-const member ==:** Normal and reversed candidates each win one argument, so C++20 calls it ambiguous.
    - **P2468 escape hatch:** A matching operator!= in the same scope stops that == from being rewritten or reversed.
    - **No == from <=>:** A hand-written <=> never provides ==, because equality can often be cheaper.
  - **Library helpers:** Function objects and exposition-only helpers built on <=>.
    - **compare_three_way:** Calls <=> and gives a strict total order over pointers.
    - **synth-three-way:** Used by pair, tuple and containers; falls back on < and yields weak_ordering.
    - **strong_order:** Gives floating point the IEEE total order, so NaNs have a place.

## Standardese Quiz Questions

### Question 1 [warmup] ([over.match.oper], [class.compare.default])

In C++23, is this program well-formed?

```cpp
#include <compare>

struct P {
  int x;
  auto operator<=>(const P& o) const { return x <=> o.x; }
};

int main() {
  P a{1}, b{1};
  return a == b;
}
```

A. Well-formed: `a == b` is rewritten as `(a <=> b) == 0`
B. Well-formed: a user-declared `operator<=>` implicitly declares `operator==`
C. Ill-formed: there is no `operator==` for `P`
D. Ill-formed: `operator<=>` with a deduced return type must be defaulted

**Answer (C):** Ill-formed: there is no `operator==` for `P`

**Why:** Equality is never rewritten in terms of `<=>`; the rewritten candidates for `==` are only reversed `operator==` functions. An `operator==` is implicitly declared only when `operator<=>` is *defaulted* and no `operator==` is declared, and this one is hand-written. A deduced `auto` return type is fine on a user-written `<=>`.

### Question 2 [warmup] ([over.match.oper], [class.eq])

In C++20 and later, what does `main` return?

```cpp
struct Q {
  int x;
  bool operator==(const Q&) const = default;
};

int main() {
  Q a{1}, b{2};
  return a != b;
}
```

A. 0
B. Nothing: ill-formed, because `Q` has no `operator!=`
C. Nothing: ill-formed, because `!=` needs a defaulted `operator<=>`
D. 1

**Answer (D):** 1

**Why:** Since C++20, `a != b` considers the rewritten candidate `!(a == b)`. The defaulted `operator==` compares `x` memberwise, giving false, so `a != b` is true and `main` returns 1. In C++17 this would have been ill-formed, which is the tempting answer; `operator<=>` plays no part in `!=`.

### Question 3 [warmup] ([expr.spaceship], [cmp.partialord])

What does this program print?

```cpp
#include <compare>
#include <cstdio>
#include <cmath>

int main() {
  double n = std::nan("");
  auto r = n <=> 1.0;
  std::printf("%d %d %d %d\n", r < 0, r == 0, r > 0,
              r == std::partial_ordering::unordered);
}
```

A. `0 0 1 0`
B. `0 0 0 1`
C. `1 0 0 0`
D. Nothing: `<=>` on a NaN is undefined behavior

**Answer (B):** `0 0 0 1`

**Why:** Built-in `<=>` on floating-point operands yields `std::partial_ordering`, and when either operand is a NaN the result is `unordered`. An unordered value compares false against literal zero with every relational operator and with `==`, so the first three are 0 and only the comparison with `unordered` is 1. There is no undefined behaviour; partial ordering exists precisely to represent this case.

### Question 4 [tricky] ([expr.spaceship], [dcl.init.list])

In C++23, what happens with this declaration?

```cpp
#include <compare>

auto r = -1 <=> 1u;
```

A. It is ill-formed
B. `r` is `std::strong_ordering::less`
C. `r` is `std::strong_ordering::greater`, because `-1` converts to a large unsigned value
D. `r` is `std::weak_ordering::less`

**Answer (A):** It is ill-formed

**Why:** For arithmetic operands, `<=>` applies the usual arithmetic conversions, and [expr.spaceship] makes the program ill-formed if a narrowing conversion is needed, other than integral to floating point. Converting `-1` to `unsigned int` is narrowing. The third option is what `-1 < 1u` effectively does, which is exactly the trap `<=>` was designed to reject.

### Question 5 [tricky] ([class.spaceship], [class.compare.default])

Is this program well-formed?

```cpp
#include <compare>

struct Legacy {
  int v;
  bool operator<(const Legacy& o) const { return v < o.v; }
  bool operator==(const Legacy& o) const { return v == o.v; }
};

struct W {
  Legacy l;
  auto operator<=>(const W&) const = default;
};

int main() {
  W a{{1}}, b{{2}};
  return a < b;
}
```

A. Well-formed: the defaulted `<=>` synthesizes a result from `<` and `==`
B. Well-formed: `a < b` falls back to `Legacy::operator<` directly
C. Ill-formed: the defaulted `operator<=>` is defined as deleted, and `a < b` uses it
D. Ill-formed: a class without `<=>` cannot be a member of a class that defaults `<=>`

**Answer (C):** Ill-formed: the defaulted `operator<=>` is defined as deleted, and `a < b` uses it

**Why:** With a deduced `auto` return type, a defaulted `operator<=>` needs `<=>` on every member; `Legacy` has none, so the function is defined as deleted. Declaring the class is fine, but `a < b` selects the deleted function through the rewritten candidate. The fallback to `==` and `<` only happens when the return type is named, such as `std::weak_ordering`, which is why the first option is tempting.

### Question 6 [tricky] ([class.spaceship], [cmp.common])

What is `decltype(M{} <=> M{})`?

```cpp
#include <compare>

struct M {
  int i;
  double d;
  auto operator<=>(const M&) const = default;
};
```

A. `std::strong_ordering`, from the first member
B. `std::weak_ordering`
C. `std::partial_ordering`
D. `auto`; the type is not fixed until the comparison is evaluated

**Answer (C):** `std::partial_ordering`

**Why:** A defaulted `operator<=>` with an `auto` return type returns the common comparison category of its member comparisons. `int <=> int` is `std::strong_ordering` and `double <=> double` is `std::partial_ordering`, and the common category is the weakest, `std::partial_ordering`. The first member does not decide the type, even though it is compared first.

### Question 7 [standardese] ([cmp.categories], [cmp.weakord], [cmp.strongord])

Which of these declarations is ill-formed?

A. `std::partial_ordering p = std::strong_ordering::less;`
B. `std::weak_ordering w = std::strong_ordering::equal;`
C. `std::partial_ordering q = std::weak_ordering::greater;`
D. `std::strong_ordering s = std::weak_ordering::equivalent;`

**Answer (D):** `std::strong_ordering s = std::weak_ordering::equivalent;`

**Why:** The comparison category types convert implicitly only towards weaker guarantees: `strong_ordering` to `weak_ordering` and `partial_ordering`, and `weak_ordering` to `partial_ordering`. Turning a weak ordering into a strong one would claim that equivalent values are interchangeable, so no conversion exists. The other three are all permitted widenings.

### Question 8 [standardese] ([over.match.oper], [expr.spaceship])

Only one comparison function exists. Which expression does the compiler evaluate for `42 < s`, and what is printed?

```cpp
#include <compare>
#include <cstdio>

struct S {
  int v;
  std::strong_ordering operator<=>(int x) const {
    std::puts("member");
    return v <=> x;
  }
};

int main() {
  S s{5};
  std::printf("%d\n", 42 < s);
}
```

A. `(42 <=> s) < 0`; prints `member` then `0`
B. `0 < (s <=> 42)`; prints `member` then `0`
C. `0 < (s <=> 42)`; prints `member` then `1`
D. None: the program is ill-formed because `int` has no `operator<=>(S)`

**Answer (B):** `0 < (s <=> 42)`; prints `member` then `0`

**Why:** For `x < y`, [over.match.oper] adds the rewritten candidate `(x <=> y) < 0` and the reversed candidate `0 < (y <=> x)`. Only the reversed form matches the member, so `42 < s` becomes `0 < (s <=> 42)`. Since 5 is less than 42, `s <=> 42` is `less`, and `0 < less` is false, so it prints `member` and `0`. The third option forgets that the reversal also flips which side of zero the result is tested on.
