On Wednesday, 16 March 2016 at 16:40:49 UTC, Shachar Shemesh wrote:

People who are marginally familiar with integer promotion will not be surprised to know that the program prints "256". What is surprising to me is that this produced neither error nor warning.


Here's a simpler example:

import std.stdio : writeln;

void main() {
    ulong MAX_VAL = 256;
    long value = -500;

    writeln(value > MAX_VAL); //prints true
}

Looks like integer promotion in D follows the same rules as C: when the types are the same size, the signed type is converted to the unsigned type. Definitely could cause an issue and deserves a warning, as you say.

It's not like you could switch the rule to being that an unsigned type is converted to the signed type. You would still get errors, just over a different range. You could instead write something like:

bool compare(long a, ulong b)
{
        if (b < long.sizeof)
                return a > cast(long)b;
        else
                return cast(float)a > cast(float)b;
}

Reply via email to