[OT] The Usual Arithmetic Confusions

Dukc ajieskola at gmail.com
Sun Feb 20 14:28:03 UTC 2022


On Saturday, 5 February 2022 at 02:43:27 UTC, Walter Bright wrote:
> On 2/4/2022 3:51 PM, Adam Ruppe wrote:
>> 
>> To reiterate:
>> 
>> C's rule: int promote, DO allow narrowing implicit conversion.
>> 
>> D's rule: int promote, do NOT allow narrowing implicit 
>> conversion unless VRP passes.
>> 
>> My proposed rule: int promote, do NOT allow narrowing implicit 
>> conversion unless VRP passes OR the requested conversion is 
>> the same as the largest input type (with literals excluded 
>> unless their value is obviously out of range).
>
> We considered that and chose not to go that route, on the 
> grounds that we were trying to minimize invisible truncation.
>

I do like Adam's proposal as well. If you're adding two shorts 
together and assigning them back to a short, there isn't really 
any surprising truncation happening, it's more like just any 
integer overflow:

```d
int a = 0x6000_0000;
int b = a+a; // overflow
short c = 0x6000;
short d = c+c; // overflow with Adam's proposal, disallowed now.
```

I can't see why that overflow would be any more surprising with 
`short` than with an `int`.

One thing that also speaks for the proposal it is 16-bit 
programming. Yes, I know that D is not designed for under 32 bits 
so 16 bits should be a secondary concern, but remember that D can 
already do that to some extent: 
https://forum.dlang.org/post/kctkzmrdhocsfummllhq@forum.dlang.org 
.

> P.S. as a pragmatic programmer, I find very little use for 
> shorts other than saving some space in a data structure. Using 
> shorts as temporaries is a code smell.




More information about the Digitalmars-d mailing list