Thread overview | |||||
---|---|---|---|---|---|
|
June 24, 2014 Compilation error while adding two shorts | ||||
---|---|---|---|---|
| ||||
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 |
June 24, 2014 Re: Compilation error while adding two shorts | ||||
---|---|---|---|---|
| ||||
Posted in reply to David Zaragoza | 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 |
June 25, 2014 Re: Compilation error while adding two shorts | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | Interesting info, I've never seen this behavior in C since the conversion is implicit as [2] notes. A simple cast resolves the problem in D: module main; int main(string[] argv){ short asd = 1; short qwe = cast(short)(asd + asd); return 0; } Thanks for your answer :) |
Copyright © 1999-2021 by the D Language Foundation