[OT] The Usual Arithmetic Confusions

Paul Backus snarwin at gmail.com
Thu Feb 3 16:25:06 UTC 2022


On Thursday, 3 February 2022 at 05:50:24 UTC, Walter Bright wrote:
> On 2/2/2022 6:25 PM, Siarhei Siamashka wrote:
>> On Thursday, 3 February 2022 at 01:05:15 UTC, Walter Bright 
>> wrote:
>>> As does:
>>>
>>>     ubyte a, b, c;
>>>     a = b | c;
>> 
>> But `a = b + c` is rejected by the compiler.
>
> That's because `b + c` may create a value that does not fit in 
> a ubyte.

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.

The inconsistency is the problem here. Having integer types 
behave differently depending on their width makes the language 
harder to learn, 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)


More information about the Digitalmars-d mailing list