Iter Ator
Iter Ator

Reputation: 9299

Are literals type-cast at compile time?

Does these lines produce the same compiled code?

double one = 1.0;
double one = 1.f;
double one = 1;

Or this three?

float one = 1.0;
float one = 1.f;
float one = 1;

Edit

Assume, that the values at the right side can be stored as a 32bit float

Upvotes: 1

Views: 383

Answers (2)

user743382
user743382

Reputation:

They're not allowed to be converted at compile time unless the compiler can prove that converting at compile time is equivalent to converting at run time. When the compiler can prove that, and for a lot of types it's easy, most compilers will perform the conversion at compile time.

But one example you give is of a conversion from a literal of type double to type float. This gets tricky. For compilers that support floating point status flags (which C compilers are required to support when the FENV_ACCESS pragma is used, even though neither gcc nor clang implement that pragma), such a conversion potentially has a side effect of raising an "inexact" exception if the conversion from double to float would lose precision. In your case, precision would not be lost, but with e.g. float f = 1.1;, it almost certainly would be. If float f = 1.1; and float f = 1.1f; have visibly different behaviour, a compiler cannot turn one into the other.

Upvotes: 9

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385264

In practice, I'd be surprised if they didn't. The statements are very simple and can be trivially resolved at compile-time.

But, strictly speaking, you cannot and should not rely on this. Semantically there are conversions at play here, so the results may not be what you expect. If your code relies on this, odds are you're doing something weird anyway.

Upvotes: 3

Related Questions