A strange div bug on Linux x86_64, (both dmd & ldc2): long -5000 / size_t 2 = 9223372036854773308

Adam D. Ruppe destructionator at gmail.com
Fri Aug 14 13:32:09 UTC 2020

On Friday, 14 August 2020 at 09:12:50 UTC, Walter Bright wrote:
> 2's complement arithmetic is intuitive for systems programmers 
> and assembler programmers

A lot of us know perfectly well how it works (at least when we 
stop and think about it for a second), but it is still easy to 
just unintentionally mix things and screw it up without realizing 
it since the edge cases may not manifest quickly.

But I do find this a little ironic given how absolutely brutal D 
is when it comes to narrowing conversions after implicit 
promotion. You know:

ushort a, b;
ushort c = a + b; // requires explicit cast!


ushort c = ushort(a + b);

complains. Gotta explicitly cast the whole parenthetical, and it 
is pretty annoying. You and I both know the CPU can do this 
trivially, in x86 asm it is just `add ax, bx`. Of course we both 
also know C promotes them to ints (ok to uints here) before any 
arithmetic and the carry bit is discarded when truncated back to 
ushort and I understand the concern the compiler is trying to 
communicate... just I don't care, I want 16 bit operations here.

So anyway I bring this up in this thread because when it comes to 
signed and unsigned, you say we need to know how two's complement 
works, this is a systems programming language. But when it comes 
to discarding carry bits on 16 bit operations, now the compiler 
treats us like this like we're ignorant fools.

Like I said, I sometimes ignorantly and foolishly mix signed and 
unsigned when I should know better. I just forget. And maybe I 
sometimes would do that with int and ushort or whatever too if 
the compiler didn't say something.

So I get why it does this.

Just it irks me and seeing the very different behavior for these 
two situations doesn't make much sense to me. Either say we need 
to know how it works and make the compiler accept it or say we 
are prone to mistakes and make the compiler complain. I find it 
hard to believe explicit 16 bit arithmetic is more prone to real 
world bugs than unsigned issues.

More information about the Digitalmars-d mailing list