3 ms·
C programmers should also be familiar with carry propagation; I see no reason they shouldn't be expected to work out the correctness of int cmp(int x, int
by pbsd 12y ago
C programmers should also be familiar with carry propagation; I see no reason they shouldn't be expected to work out the correctness of
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);
}
- bluecalm 12y agoThe difference is that: 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.
- CamperBob2 12y agoI write (and read) about 20,000 lines of C(++) a year, and have for the last 20 years. I've never seen that done.
- SamReidHughes 12y agoThat doesn't mean the expression is unreadable. It is still extremely straightforward in what it does.
- dllthomas 12y agoThe real difference is that it's simple. There are only 11 symbols in the expression, only two things that can vary, and only three interesting cases. As opposed to 129 symbols and some large number of interesting cases.