Let Go, Standard Library From Community
Stephen Waits
steve at waits.net
Wed Apr 18 17:05:12 PDT 2007
Derek Parnell wrote:
> return x >= 0 ? x : -x;
Or, if we're going to get that picky, and you want to prefer +0 over -0,
then you can also eliminate the equality test.
return x < 0 ? -x : x;
I agree with you.. portability is preferred here, considering the
non-existent performance difference.
I'd even go as far as saying that using bit twiddling in this specific
case is the "junior mistake".
Why? Because it assumes that the compiler isn't already taking care of
this for you.
In C++, my gcc4 already optimizes both -x and x *= -1 into optimal code,
similar to the bit-twiddling Dan suggested. I have to assume we can get
the same under D, whether it exists today or not.
--Steve
More information about the Digitalmars-d
mailing list