Is it always necessary to use float literals when performing arithmetic on float variables in C ++?

I see a lot of C ++ code that has lines like:

float a = 2; float x = a + 1.0f; float b = 3.0f * a; float c = 2.0f * (1.0f - a); 

Are these .0f after these literals are really needed? Would you lose numerical accuracy if you omit them?

I thought you would need them if you have a line like this:

 float a = 10; float x = 1 / a; 

where you should use 1.0f , right?

+6
source share
4 answers

You will need to use it in the following case:

 float x = 1/3; 

1 or 3 must have .0 , otherwise x will always be 0.

+6
source

If a is int , these two lines are definitely not equivalent:

float b = 3.0f * a;
float b = 3 * a;

The second will silently overflow if a too large, since the right-hand side is evaluated using integer arithmetic. But the first is absolutely safe.

But if a is a float , as in your examples, then the two expressions are equivalent. Which one you use is a matter of personal preference; the first is probably more hygienic.

+1
source

It depends on what you do with the numbers. A floating point literal type with f or f is of type float . A floating point literal type without a suffix is ​​of type double . As a result, there may be slight differences when using the suffix f compared to not using it.

As long as the subexpression includes at least one floating-point type object, this probably doesn't matter much. It is more important to use suffixes with integers, which should be interpreted as floating points. If there is no floating point value in the subexpression, integer arithmetic is used. This can have serious consequences, because the result will be whole.

0
source
 float b = 3.0f * a; 

Sometimes this is done because you want to make sure that 3.0 is created as a float, not as a double.

-1
source

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


All Articles