Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the three-way comparison operator different from subtraction?

There's a new comparison operator <=> in C++20. However I think in most cases a simple subtraction works well:

int my_strcmp(const char *a, const char *b) {     while (*a == *b && *a != 0 && *b != 0) {         a++, b++;     }     // Version 1     return *a - *b;     // Version 2     return *a <=> *b;     // Version 3     return ((*a > *b) - (*a < *b)); } 

They have the same effect. I can't really understand the difference.

like image 310
iBug Avatar asked Dec 31 '17 13:12

iBug


People also ask

What is the different comparison operator?

Comparison operators — operators that compare values and return true or false . The operators include: > , < , >= , <= , === , and !== . Logical operators — operators that combine multiple boolean expressions or values and provide a single boolean output.

What does === comparison operator do?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

What is three-way comparison operator C++?

The three-way comparison operator “<=>” is called a spaceship operator. The spaceship operator determines for two objects A and B whether A < B, A = B, or A > B. The spaceship operator or the compiler can auto-generate it for us.


1 Answers

The operator solves the problem with numeric overflow that you get with subtraction: if you subtract a large positive number from a negative that is close to INT_MIN, you get a number that cannot be represented as an int, thus causing undefined behavior.

Although version 3 is free from this problem, it utterly lacks readability: it would take some time to understand by someone who has never seen this trick before. <=> operator fixes the readability problem, too.

This is only one problem addressed by the new operator. Section 2.2.3 of Herb Sutter's Consistent comparison paper talks about the use of <=> with other data types of the language where subtraction may produce inconsistent results.

like image 184
Sergey Kalinichenko Avatar answered Oct 12 '22 01:10

Sergey Kalinichenko