Compilation error while adding two shorts
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jun 23 23:12:54 PDT 2014
On 06/23/2014 10:03 PM, David Zaragoza wrote:> Hello
>
> I'm trying to compile the following program:
>
> module main;
>
> int main(string[] argv){
> short asd = 1;
> short qwe = asd + asd;
> return 0;
> }
>
> And the compiler gives this error:
>
> C:\David>dmd simple
> simple.d(5): Error: cannot implicitly convert expression (cast(int)asd +
> cast(in
> t)asd) of type int to short
>
> Why is there a cast if I'm adding to shorts?
>
> Regards
This is a common gotcha of system languages like C, C++, and D.
Operations like + are never executed in types like 'short'.[1] Since the
result of that + is int, the compiler does not allow assigning the value
back to a short, which can lose data.
However, in this case it is clear that the value of asd is known to be 1
at compile time and that there will not be data loss. The D compilers
apply what is known as 'value range propagation'[2], which should take
care of your issue. I guess the use in your program is too complicated
for the current compiler.
Ali
[1] See both "Integer Promotions" and "Usual Arithmetic Conversions" here:
http://dlang.org/type.html
[2] "Value Range Propagation"
http://www.drdobbs.com/tools/value-range-propagation/229300211
More information about the Digitalmars-d-learn
mailing list