Rewriting Expressions

Discover how the comparison expressions trigger a compiler to generate the spaceship expression.

When the compiler sees something such as a < b, it rewrites it to (a <=> b) < 0 using the spaceship operator. Of course, the rule applies to all six comparison operators:

a OP b becomes (a <=> b) OP 0. It’s even better. If there is no conversion of the type(a) to type(b), the compiler generates the new expression 0 OP (b <=> a).

For example, this means for the less-than operator, if (a <=> b) < 0 does not work, the compiler generates 0 < (b <=> a). In essence, the compiler takes care of the symmetry of the comparison operators.

Here are a few examples of rewriting expressions:

Get hands-on with 1200+ tech skills courses.