[OT] The Usual Arithmetic Confusions

Walter Bright newshound2 at digitalmars.com
Thu Feb 3 05:50:24 UTC 2022


On 2/2/2022 6:25 PM, Siarhei Siamashka wrote:
> On Thursday, 3 February 2022 at 01:05:15 UTC, Walter Bright wrote:
>> On 2/2/2022 3:37 PM, Adam Ruppe wrote:
>>> The value range propagation only works inside single expressions and is too 
>>> conservative to help much in real code.
>>
>> I find it works well. For example,
>>
>>     int i;
>>     byte b = i & 0xFF;
>>
>> passes without complaint with VRP.
> 
> No, it's doesn't pass: `Error: cannot implicitly convert expression i & 255 of 
> type int to byte`.

My mistake. b should have been declared as ubyte.

> 
>> 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.

> Maybe I'm expecting modular 
> wrap-around arithmetic here? Or maybe I know the possible range of `b` and `c` 
> variables and I'm sure that no overflows are possible? But the compiler requires 
> an explicit cast. Why is it getting in the way?

Because C bugs where there are hidden truncations to bytes are a problem.


> Also if the type is changed to `uint` in the same example, then the compiler is 
> suddenly okay with that and doesn't demand casting to `ulong`. This is 
> inconsistent.

It follows the C integral promotion rules. This is for consistent arithmetic 
behavior with C.

  You will probably say that it's because of integer promotion and
> 32-bit size is a special snowflake. But if the intention is to catch bugs at the 
> compilation stage, then adding two ubytes together and adding two uints together 
> isn't very different (both of these operations can potentially overflow). What's 
> the reason to be anal about ubytes?

We do the best we can. There really is no solution that doesn't have its own issues.

> The other modern programming languages can catch arithmetic overflows at 
> runtime. And allow to opt out of these checks in performance critical parts of 
> the code.

They just have other problems. VRP makes many implicit conversions to bytes 
safely possible.


More information about the Digitalmars-d mailing list