Comment by ryao
1 month ago
My comment had been meant for C, but it should apply to C++ too even when operator overloading is used, provided the comparisons are simple and inlined. If you add overloads for the > and < operators in your string example to a place where they would inline, and the overload compares .length(), this should simplify. For example, godbolt shows that CMP(X, Y) == 0 is optimized to one mov instruction and one cmp instruction despite operator overloads when I implement your string example:
https://godbolt.org/z/nGbPhz86q
If you did not inline the operator overloads and had them in another compilation unit, do not expect this to simplify (unless you use LTO).
If you have compound comparators in the operator overloads (such that on equality in one field, it considers a second for a tie breaker), I would not expect it to simplify, although the compiler could surprise me.
I was more thinking of eg lexicographic comparisons of strings, not just comparing by length.
Yes, if you have a smart enough compiler, or a simple enough comparison, this will simplify.
You could use CMP(A, B) as part of your lexographic comparison and then have it output the result of the first non-zero result (unless you find both strings are equal, in which case, you would output zero) when comparing characters.
If you implement the operators, you can use CMP(A, B) to turn it into a three value output, since it works solely using Boolean logic, but I would be surprised if it simplified. I am half prepared to be surprised since the compiler might do some CSE after inlining and then do some other transformation. That said, you really only want to use CMP(A, B) for numerical comparisons.
Yes, you can definitely manually define it. I was talking about what we can reasonably expect the compiler to figure out on its own.