So why double to float conversion is implicit ?

Basile B. b2.temp at gmx.com
Fri Oct 27 07:54:48 UTC 2017


On Tuesday, 24 October 2017 at 15:29:38 UTC, Basile B. wrote:
> On Saturday, 21 October 2017 at 20:17:12 UTC, NX wrote:
>> I was working on some sort of math library for use in 
>> graphical computing and I wrote something like this:
>>
>> const float PiOver2 = (atan(1.0) * 4) / 2;
>>
>> Interestingly enough, I realized that atan() returns double 
>> (in this case) but wait, it's assigned to a float variable! 
>> Compiler didn't even emit warnings, let alone errors.
>>
>> I see no reason as to why would this be legal in this century, 
>> especially in D.
>> So can someone tell me what's the argument against this?
>> Why type conversions differ between integral and floating 
>> types?
>> Why can't I assign a long to an int but it's fine when 
>> assigning double to float?
>>
>> I think this is a serious topic and needs clarification.
>
> I think that the rationale for allowing that is that you can 
> feed the FPU with high precision values to get a better 
> internal accuracy (temp values stored in ST0-ST7). At the end, 
> even if there's a truncation the result is more accurate that 
> if you would have feed the FPU with parameters of the same size 
> as the result.

I'm currently using the compiler version that includes the 
warning:

https://github.com/dlang/dmd/pull/7240

and discovered that it's actually not only a problem of 
truncation.
For

```
float foo(float f)
{
     f *= 0.5;
     return f;
}
```


DMD generates


```
push rbp
mov rbp, rsp
cvtss2sd xmm1, xmm0 ; promotion
movsd xmm2, qword ptr [<addr of constant>]
mulsd xmm1, xmm2
cvtsd2ss xmm0, xmm1 ; truncation
pop rbp
ret
```

as you can see, the parameter is promoted to double because of 
the constant and then the result is converted back to single. The 
two instructions obviously disappear when the constant get the 
float suffix, and the compiler warning helped you to save a few 
cycles.


More information about the Digitalmars-d mailing list