Best practices for performance

PWR044: Avoid unnecessary floating-point data conversions involving constants

Issue #

Mixing float type value with double type constants results in unnecessary data conversions.

Actions #

Instead of the double constant, explicitly specify a float constant by appending the constant with f.

Relevance #

According to the C/C++ standard, binary operators (+, -, *, /, %, <, >, <=, >=, ==, !=) involving a float value and a double constant can often result in unnecessary data conversions: the float value is first promoted to a double, then the binary operator is evaluated. Most of the time this is not the intended behavior.

Code examples #

Have a look at the following code:

float calc_const(float a) {
    return a * 2.2;

During the evaluation of the expression a * 2.2, the following happens:

  • first, the floating point in variable a is promoted from float to double;
  • second, multiplication is performed using doubles; and third, the resulting value is converted back to float.

In this particular example, there are two unnecessary conversions: one is promoting a to double, and the other is promoting the result of multiplication a * 2.2 back to float. The solution is to use a float constant 2.2f instead of the double constant 2.2.

float calc_const(float a) {
    return a * 2.2f;

Related resources #

References #