4 ms·
> C++ spaceship operator > (A <=> B) < 0 is true if A < B > (A <=> B) > 0 is true if A > B > (A <=> B) == 0 is true if A and B are equal/equivalent. TIL of
by moffkalast 2y ago
> C++ spaceship operator
> (A <=> B) < 0 is true if A < B
> (A <=> B) > 0 is true if A > B
> (A <=> B) == 0 is true if A and B are equal/equivalent.
TIL of the spaceship operator. Was this added as an april fools?
- samatman 2y agoThis is one of the oldest computer operators in the game: the arithmetic IF statement from FORTRAN. It's useful for stable-sorting collections with a single test. Also, overloading <=> for a type, gives all comparison operators "for free": ==, !=, <, <=, >=, >
- pklausler 2y agoIt also has no good definition for its semantics when presented with a NaN.
- sagarm 2y agoYou would use a partial ordering: https://en.cppreference.com/w/cpp/utility/compare/partial_ordering https://en.cppreference.com/w/cpp/utility/compare/partial_or...
- pklausler 2y agoHow would that apply to Fortran’s arithmetic IF statement? It goes to one label for a negative value, or to a second label for a zero, or to a third label for positive. A NaN is in none of these categories.
- moffkalast 2y agoI mean maybe I'm missing something but it seems like it behaves exactly the same way as subtraction? At least for integers it's definitely the same, for floats I imagine it might handle equals better?
- samatman 2y agoC++ has operator overloading, so you can define the spaceship for any class, and get every comparison operator from the fallback definitions, which use `<=>` in some obvious ways.
- sagarm 2y agoThe three-way comparison operator just needs to return a ternary, and many comparisons boil down to integer subtraction. strcmp is also defined this way. In C++20 the compiler will automatically use the spaceship operator to implement other comparisons if it is available, so it's a significant convenience.