Opinions: The Best and Worst of D (for a lecture/talk I intend to give)
Dominikus Dittes Scherkl via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jul 10 01:59:08 PDT 2014
On Wednesday, 9 July 2014 at 19:54:47 UTC, H. S. Teoh via
Digitalmars-d-learn wrote:
> [...]
> The problem is that the function needs to return
> int, but given two uints, their difference may be
> greater than int.max, so simply subtracting them
> will not work. So the best I can come up with is:
>
> int compare2(int x, uint y)
> {
> return (x < 0) ? -1 :
> (y > int.max) ? -1 :
> (x - y);
> }
>
> which requires 2 comparisons.
Hmm. Diff works for compare(int,int).
So how about this:
int compare2(int x, uint y)
{
return (y > int.max) ? -1 : (x - cast(int)y);
}
int compare2(uint x, int y)
{
return (x > int.max) ? -1 : (cast(int)x - y);
}
More information about the Digitalmars-d-learn
mailing list