0

In C++,the type of floating-point literals is double by default;

auto dval = 3.14;    // dval is a double

So,in the statement float fval = 3.14 , 3.14 -> float means double -> float?


Another similar question:

float fval = ival + 3.14;

what type conversion is happening here

  • are you asking what is the official term for what happens in `float fval = 3.14;` ? I mean `float fval` certainly is a `float`. – 463035818_is_not_an_ai Jan 21 '22 at 09:21
  • It's an implicit cast - there's some details here https://stackoverflow.com/questions/42145321/why-using-double-and-then-cast-to-float – doctorlove Jan 21 '22 at 09:25
  • what is `ival` ? The second question is also not quite clear – 463035818_is_not_an_ai Jan 21 '22 at 09:25
  • 1
    `3.14` is a `double`. `3.14f` is a `float`. Are you asking if `float fval = 3.14;` performs a conversion from `double` to `float` ? – WhozCraig Jan 21 '22 at 09:26
  • 2
    @doctorlove There is no such thing as "implicit cast", casts are explicit conversions by definition. – n. m. could be an AI Jan 21 '22 at 09:29
  • In `float fval = 3.14`, `3.14` is a literal with type `double` that is implicitly converted to `float` and the result of that conversion used to initialise `fval` (or a result *as if* that conversion and initialisation occurred in sequence). Some compilers issue warnings on this (e.g. a `double` can represent values that a `float` cannot, and the compiler may warn that converting `double` to `float` may lose precision). Your second question is unclear, since you haven't specified what `ival` is. – Peter Jan 21 '22 at 09:33
  • 1
    If you use gcc or clang, add `-Wconversion` flag and see the output, you'll see what's happening. – alagner Jan 21 '22 at 09:35
  • It's not just decimal literals, also applies to hex literals like `0x1.p8` (==1.5 decimal) – MSalters Jan 21 '22 at 11:26

1 Answers1

2

Yes. In the declaration float fval = 3.14 the initialiser is implicitly converted from double to float.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • In my knowledge, implicit type conversion is small-to-large conversion, but double takes up more bytes than float. Why is there a conflict here? – Yanyu shen Jan 25 '22 at 12:12
  • @Yanyushen You seem to have misunderstood what an implicit type conversion means. It's also unclear what you mean by "conflict". – eerorika Jan 25 '22 at 13:00