Implicit conversion rules

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Oct 21 12:07:23 PDT 2015


On Wednesday, October 21, 2015 07:53 PM, Sigg wrote:

>      void func() {
>          int a = -10;
>          ulong b = 0;
>          ulong c = a + b;
>          writefln("%s", c);
>      }
> 
>      out: 18446744073709551574
> 
> But shouldn't declaring c as auto force compiler to go extra step
> and "properly" deduce result of the "a + b" expression, since its
> already as far as I understand doing magic in the background?
> Basically try to cast rvalues to narrowest type without losing
> precision before evaluating expression.

The problem is of course that int and ulong have no common super type, at 
least not in the primitive integer types. int supports negative values, 
ulong supports values greater than long.max.

As far as I understand, you'd like the compiler to see the values of `a` and 
`b` (-10, 0), figure out that the result is negative, and then make `c` 
signed based on that. That's not how D rolls. The same code must compile 
when the values in `a` and `b` come from run time input. So the type of the 
addition cannot depend on the values of the operands, only on their types.

Or maybe you'd expect an `auto` variable to be able to hold both negative 
and very large values? But `auto` is not a special type, it's just a 
shorthand for typeof(right-hand side). That means, `auto` variables still 
get one specific static type, like int or ulong.

std.bigint and core.checkedint may be of interest to you, if you prefer 
safer operations over faster ones.

http://dlang.org/phobos/std_bigint.html
http://dlang.org/phobos/core_checkedint.html



More information about the Digitalmars-d-learn mailing list