Opinions: The Best and Worst of D (for a lecture/talk I intend to give)
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jul 9 11:06:08 PDT 2014
On Wednesday, 9 July 2014 at 17:13:21 UTC, H. S. Teoh via
Digitalmars-d-learn wrote:
> For the comparison s < u, where s is a signed value and u is an
> unsigned
> value, whenever s is negative, the return value of opCmp must be
> negative. Assuming 2's-complement representation of integers,
> this
> means we simply copy the MSB of s (i.e., the sign bit) to the
> result. So
> we can implement s < u as:
>
> enum signbitMask = 1u << (s.sizeof*8 - 1); // this is a
> compile-time constant
> return (s - u) | (s & signbitMask); // look ma, no branches!
This is a problem, isn't it:
void main()
{
assert(cmp(0, uint.max) < 0); /* fails */
}
int cmp(int s, uint u)
{
enum signbitMask = 1u << (s.sizeof*8 - 1); // this is a
compile-time constant
return (s - u) | (s & signbitMask); // look ma, no branches!
}
More information about the Digitalmars-d-learn
mailing list