2

Dear fellow stackoverflowers,

Is there some kind of guarantee that coercing a float type to a "wider" one, always yields the same result as performing the according static_cast?

Here an example:

float f = <any float>;
double a = f;
double b = static_cast<double>(f);

// does this always hold?
EXPECT_TRUE(a==b);

Thank you for the information.

Simbi
  • 992
  • 3
  • 13
  • 29
  • 1
    This is explicitely not true for NaNs. As NaNs are defined to not equal anything _including themselves_. But thats not really what your question is asking so just adding as a comment. – Mike Vine Apr 23 '19 at 12:09
  • 1
    I'm curious what makes you think it could be different? – Borgleader Apr 23 '19 at 12:09
  • 1
    gcc will create the same assembler instruction out of it: https://godbolt.org/z/i7K_vw – mch Apr 23 '19 at 12:12
  • Note that `double` can hold any value of `float` if represented according to IEEE 754. There is therefore no loss of precision (no rounding, etc.). – Daniel Langr Apr 23 '19 at 12:17
  • @user1810087 Nothing? Really? – Tom Apr 23 '19 at 12:18
  • related: https://stackoverflow.com/questions/868306/what-is-the-difference-between-static-cast-and-implicit-cast – NathanOliver Apr 23 '19 at 12:25

1 Answers1

4

Does float type coercion always yield the same result as static_cast?

It seems that by type coercion, you refer to implicit conversion. The answer is yes: If there is an implicit conversion from one type to another, then static cast performs that same conversion.

eerorika
  • 232,697
  • 12
  • 197
  • 326