Do all floats double?

I am reading a tutorial that says the following:

C ++ treats all floating point numbers that you enter in the program source code (for example, 7.33 and 0.0975) as double default values.

I find it a little strange and have never heard of it. Seems wasteful? Why get extra accuracy if you don't specify it? Why do two different types mean the same thing? How about a long double?

+6
source share
3 answers

This only applies to floating point literals .

This is the same as saying that any integer that you write in code is always treated as a (signed) int . Once you assign this to a variable, you will get the type of the variable.

However, when using stand-alone literals in a calculation, you get the literal type for this calculation, potentially causing implicit type conversions:

 float f = 3.141; // f is of type float, even though the literal was double auto d = f * 2.0; // d will be of type double because of the literal 2.0 auto f2 = f * 2.0f; // f2 will be of type float again 

The calculation in the second line includes two different types: The type of the variable f is float . Although it was built from a double literal, the type of the variable is what counts. The literal type 2.0 , on the other hand, is double and therefore triggers an implicit conversion for computation. Therefore, the actual multiplication is performed as a multiplication by two double s.

If you want a particular value to have a specific type, use the appropriate literal.

+7
source

This is part of the language specification. If you want to double, write:

 auto a = 12.3; 

If you want a float, write:

 auto a = 12.3f; 

If you want a long double, write:

 auto a = 12.3L; 

Source: MSDN

The whole topic is described in detail in the C ++ standard in chapter 2.14 Literals .

+20
source

I really think the text in the book is correct. I rephrase a little:

By default vald with a floating point, for example 12.3 , is double .

In other words, if you do not add the letter "f" at the end of the number to make it 12.3f , it is really double.

In most cases (if floating point calculations make up only a small part of the code), this is not much different, but if you have floating point variables and use double constants to initialize and compare, an additional conversion from float to double . And, of course, the storage needed for constants will, for example, be larger.

+4
source

Source: https://habr.com/ru/post/948045/


All Articles