regarding what seems (to me) unnecessary casts on integer expressions

Adam D. Ruppe destructionator at gmail.com
Sat Jun 5 03:01:19 UTC 2021


On Saturday, 5 June 2021 at 02:38:50 UTC, someone wrote:
> Furthermore, if, **at least**, there was a way to clearly state 
> what is short (eg 1S a la 1L) things will improve a lot

That actually doesn't matter. The compiler actually will 
automatically type it to the most narrow thing it fits. The 
implementation there is actually quite nice - inside a single 
expression, the compiler tracks the possible range.

Try:

ubyte a = 5 + 3; // just works, it knows 5+3 = 8 which can be byte

ubyte b = a & 0xff; // also works, it knows the mask limits the 
range


And various combinations like that. It works as long as it is in 
one statement.

But if you cross them:

ubyte c = a + 1;

Now it assumes a might be the maximum of 255... and 255 + 1 
doesn't fit in the ubyte, thus it will not allow the assignment 
back.


Masking operations are a possible alternative to casting btw... 
but still a hassle.

> ushort a; a = cast(ushort) a - cast(ushort) 1;

This doesn't do anything since the promotion is done  anyway. The 
compiler already knows both are ushort there, it is the 
arithmetic that assumes worst case scenario.


> ushort a; a = cast(ushort)(a - 1);

this does work though.

a -= 1; // also works

> At first sight I got the impression that any type could be 
> unambiguously stated in D. Seems I was wrong.

Again, it is not the type of the literal that is the problem.

D follows the C rule that all arithmetic promotes. (Seriously, 
try it in C, it also converts to int first before doing an add or 
subtract.)

But C allows it to convert back without hassle, so it is easy to 
ignore this annoying promotion thing. D only allows the 
conversion back if the compiler can prove it fits.

> for a string "" should not the same as null

its not. They're very similar but it is NOT the same. Check the 
.ptr property.

> and 0 for a integer should not be the same as null

Its not. The type system won't allow those to cross.

> and this is obviously **really useful** for database apps and a 
> lot of other things.

I've done tons of database apps in D, I've been doing web stuff 
with D since 2008. There's various ways to do nullable sql, it 
isn't a big problem.


More information about the Digitalmars-d-learn mailing list