简体   繁体   中英

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

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 eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM