Let Go, Standard Library From Community
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Wed Apr 18 12:40:51 PDT 2007
Dan wrote:
>
> Oh my...
>
> I went through tango.core.Array and tango.math.Math and personally found several rather junior mistakes like:
>
> int abs(int x){
> return x > 0? x : -x;
> // should be: return x &= 0x7FFF_FFFF;
> }
...
That's *so* wrong...
You may want to save yourself some embarrassment by checking code before
you post it here:
=====
$ cat test.d
import std.stdio;
int abs(int x) {
return x &= 0x7fff_ffff;
}
void main() {
writefln(abs(-2));
}
$ dmd -run test.d
2147483646
=====
hint: abs(-2) != 2147483646 :P
(Most computers use a representation called "two's complement" to store
signed integers. See http://en.wikipedia.org/wiki/Two's_complement for
details)
Though returning an _unsigned_ integer instead of a signed one would
arguably improve the "abs" function. (Try calling the current version
with int.min to see what I mean)
More information about the Digitalmars-d
mailing list