3-way comparison operator (Space Ship Operator) in C++ 20
In computer science, a three-way comparison, also known as trichotomous comparison, takes two values A and B belonging to a type with a total order and determines whether A < B, A = B, or A > B in a single operation, in accordance with the mathematical law of trichotomy. In this article, we’ll explore the significance of three-way comparison in the field of computer science, its applications in machine-level computation, and how it’s implemented in high-level programming languages. Whether you’re a seasoned pro or just starting out, get ready to level up your skills with the power of three-way comparison!
In mathematics, trichotomy refers to the property of total order, which states that given any two elements, they can be compared in three possible ways: less than, equal to, or greater than. Three-way comparison extends this concept to computer science, enabling the determination of the relative ordering of two values using a single operation.
Trichotomy and Exceptions in Comparison Operations in Primitive Types
At the machine level, many processors provide instruction sets that support three-way comparison operations on primitive types. For example, processors with signed integers based on sign-and-magnitude or one’s complement representation can adopt a consistent total order to ensure trichotomy holds. In such cases, the comparison of positive and negative zero values should result in either -0 = +0 or -0 < +0. However, floating-point types introduce an exception to trichotomy due to the presence of special values like “NaN” (Not a Number). Comparisons involving NaN always yield false results, including x < NaN, x > NaN, and x = NaN.
In high-level programming languages, the concept of three-way comparison is implemented through various constructs and functions.
C Language
In C, the functions strcmp and memcmp are commonly used for performing three-way comparisons between strings and memory buffers, respectively. These functions return a negative number if the first argument is lexicographically smaller than the second, zero if the arguments are equal, and a positive number otherwise. This convention of returning the “sign of the difference” is further extended to arbitrary comparison functions by the standard sorting function qsort. The qsort function requires the comparison function to abide by this convention.
#include <stdio.h>
#include <string.h>
int memcmp_three_way(const void* s1, const void* s2, size_t n) {
const unsigned char *p1 = s1, *p2 = s2;
int result = 0;
while (n-- > 0 && result == 0) {
result = (*p1 > *p2) - (*p1 < *p2);
p1++;
p2++;
}
return result;
}
void main() {
char str1[] = "banana";
char str2[] = "apple";
int cmp_result = memcmp_three_way(str1, str2, sizeof(str1));
if (cmp_result == 0)
printf("str1 and str2 are equal\n");
else if (cmp_result < 0)
printf("str1 is less than str2\n");
else
printf("str1 is greater than str2\n");
}
// str1 is greater than str2
C++ Language
The C++ language, starting from the C++20 revision, introduces a powerful tool for three-way comparison known as the “spaceship operator” (<=>). The spaceship operator returns the sign of the difference between two operands and can also yield different types (convertible to signed integers) based on the strictness of the comparison. This operator simplifies the implementation of comparison functions and facilitates the sorting of complex data structures.
// GCC 12.1 (C++ 20)
#include <compare>
#include <iostream>
using namespace std;
struct Person {
string name;
int age;
auto operator<=>(const Person&) const = default;
};
int main() {
Person john {"John", 30};
Person jane {"Jane", 25};
auto result = john <=> jane;
if (result > 0)
cout << john.name << " is older than " << jane.name << endl;
else if (result < 0)
cout << john.name << " is younger than " << jane.name << endl;
else
cout << john.name << " and " << jane.name << " are of the same age" << endl;
return 0;
}
Conclusion
Three-way comparison is a powerhouse concept in computer science that turbocharges evaluations of value relationships. With just one operation, it can determine if a value is less than, equal to, or greater than another. This means smoother, more efficient computation and optimized code — the backbone of robust, scalable software solutions. So if you want to level up your programming skills, mastering three-way comparison is a must.
Check out the documentation on cppreference.com to learn more about this using following link!
Experience the magic of sorting in C like never before with the ultimate qsort implementation on GitHub — click the link to discover more!