challenge: implement the max function
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Thu Jan 25 01:11:46 PST 2007
Andrei Alexandrescu (See Website For Email) wrote:
> Speaking of which, sometimes more than one comparison is necessary.
> Consider:
>
> int a = -1;
> uint b = 3000000000; // three billion
> auto x = max(a, b);
>
> What this code wants is unambiguous: max between an int and a uint is
> always computable and returns a uint. But notice that converting either
> of a or b to the other's type will yield the wrong result: cast(uint)a
> is greater than b, and cast(int)b is smaller than a. The right solution
> for mixed-sign max is (nontemplated):
>
> uint max(int a, uint b)
> {
> if (a <= 0) return b;
> auto c = cast(uint) a;
> return c > a ? c : a;
> }
In the above case, of course, you can also get away with casting both to
long ;).
Signed-unsigned comparisons are one of those little annoyances. It has
been proposed in the past that such comparisons should always return the
correct result, by automatically expanding them to something similar to
what you have done manually in above code (unless the compiler can
determine it's not necessary, of course).
More information about the Digitalmars-d
mailing list