[OT] The Usual Arithmetic Confusions
Walter Bright
newshound2 at digitalmars.com
Fri Feb 4 04:28:37 UTC 2022
On 2/3/2022 8:25 AM, Paul Backus wrote:
> And yet:
>
> int a, b, c;
> a = b + c;
>
> `b + c` may create a value that does not fit in an int, but instead of the
> rejecting the code, the compiler accepts it and allows the result to wrap around.
Yup.
> The inconsistency is the problem here. Having integer types behave differently
> depending on their width makes the language harder to learn,
It's not really that hard - it's about two or three sentences. As long as one
understands 2s-complement arithmetic. If one doesn't understand 2s-complement,
and assumes it works like 3rd grade arithmetic, I agree it can be baffling.
There's really no fix for that other than making the effort to understand
2s-complement. Some noble attempts:
Java: disallowed all unsigned types. Wound up having to add that back in as a hack.
Python: numbers can grow arbitrarily large without loss of precision. Makes your
code slow, though.
Javascript: everything is a double precision floating point value! Makes for all
kinds of other problems. If there's anything people understand less (a lot less)
than 2s-complement, it's floating point.
> and forces generic
> code to add special cases for narrow integers, like this one in `std.math.abs`:
>
> static if (is(immutable Num == immutable short) || is(immutable Num ==
> immutable byte))
> return x >= 0 ? x : cast(Num) -int(x);
> else
> return x >= 0 ? x : -x;
>
> (Source:
> https://github.com/dlang/phobos/blob/v2.098.1/std/math/algebraic.d#L56-L59)
That's because adding abs(short) and abs(byte) was a giant mistake. There's good
reason these functions never appeared in C.
Trying to hide the reality of how computer integer arithmetic works, and how
integral promotions work, is a prescription for endless frustration and
inevitable failure.
If anybody has questions about how 2s complement arithmetic works, and how
integral promotions work, I'll be happy to answer them.
More information about the Digitalmars-d
mailing list