Should you be able to initialize a float with a char?

Paul Backus snarwin at gmail.com
Wed May 18 22:24:18 UTC 2022


On Wednesday, 18 May 2022 at 22:11:34 UTC, max haughton wrote:
> For example:
>
> float x = 'a';
>
> Currently compiles. I had no idea that it does but I was 
> implementing this pattern in SDC and lo and behold it does (and 
> thus sdc has to support it).
>
> Should it? Implicit conversions and implicit-anything around 
> floats seem to be very undocumented in the specification too.

Under ["integer promotions"][1], the spec says that `char` can 
implicitly convert to `int`. Under ["usual arithmetic 
conversions"][2], the spec says (by implication) that all 
arithmetic types can implicitly convert to `float`. "Arithmetic 
type" is not explicitly defined by the spec, but [in the C99 
standard][3] it means "integer and floating types." It's probably 
safe to assume the same definition applies to D.

So I would say that according to the spec, the answer is "yes, 
the example should work." Though it is rather surprising.

[1]: https://dlang.org/spec/type.html#integer-promotions
[2]: https://dlang.org/spec/type.html#usual-arithmetic-conversions
[3]: http://port70.net/~nsz/c/c99/n1256.html#6.2.5p18


More information about the Digitalmars-d mailing list