The previous commenter may have entered that into say, a Python console where it wouldn't exhibit that behavior.
The previous commenter may have entered that into say, a Python console where it wouldn't exhibit that behavior.
So what then is the CORRECT way of doing this comparison in C, avoiding potential overflow pitfalls?
return (x > y) - (x < y);From GCC documentation:
>>-findirect-inlining Inline also indirect calls that are discovered to be known at compile time thanks to previous inlining. This option has any effect only when inlining itself is turned on by the -finline-functions or -finline-small-functions options.
Enabled at level -O2.For many data types, like time, that will normally never happen, making subtraction the safest no-brainpower-needed approach. If in doubt, use the next larger integer type.
return (x > y) - (x < y);
Quick. What's that do?What will the next person who looks at the code think it does?
I think tptacek must be ready to have his bib changed, with all the drooling he must be doing.
int cmp(int x, int y) {
const unsigned a = x;
const unsigned b = y;
const unsigned s = sizeof x * 8 - 1;
return ((b^((b^(b-a))&(a^(b-a))))>>s)&~-((a^((a^(a-b))&(b^(a-b))))>>s)^-((a^((a^(a-b))&(b^(a-b))))>>s)&~-((b^((b^(b-a))&(a^(b-a))))>>s);
} return (x > y) - (x < y);
Is a common expression which is very efficient (why else would you write anything in C if you don't care about code being fast/efficient?) and what you proposed is neither.Duh.