Difference between 2.0 and 2.0f (explicit float vs double literals)

I have questions about placing f next to literal values. I know that it defines it as a float , but do I really need it? Is this 2.0f * 2.0f faster or compiled than 2.0 * 2.0 ? Is an expression like float a = 2.0; compiled differently than float a = 2.0f; ?

+9
c ++ c
Sep 12 '10 at 22:19
source share
3 answers

Sometimes you need to explicitly specify a float type, as in the following case

 float f = ...; float r = std::max(f, 42.0); // won't work; (float, double). float r = std::max(f, 42.0f); // works: both have same type 
+19
Sep 12 '10 at 10:22
source share

I rarely talk about speed (at least directly), but that otherwise the compiler will warn you about converting double to float .

+6
Sep 12 '10 at 22:21
source share

AFAIK, on ​​"regular" PCs (x86 with x87-like mathematical coprocessor) the difference in speed does not matter, because the calculations are internally performed in any case with an accuracy of 80 bits.

Floats can take on meaning when you have large arrays of floating point numbers for control (scientific calculations or similar things), so having a smaller data type can be convenient for using less memory or for quick reading from RAM / disk .

It may also be useful to use floats instead of doubles on machines that lack a floating point unit (for example, most microcontrollers), where all floating point arithmetic is performed in software using the code inserted by the compiler; in this case, there may be a speed gain acting on the floats (and in such environments every bit of memory also often occurs).

On IMO computers, you can simply use double in "normal" contexts, just try to avoid mixing data types (double, float, ints, ...) in one expression to avoid unnecessary costly conversions. In any case, with literals, the compiler must be smart enough to perform the conversion at compile time.

+3
Sep 12 '10 at 10:29
source share



All Articles