Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The C Standard, subclause F.6 states:  [ISO/IEC 9899:2011], states:

If the return expression is evaluated in a floating-point format different from the return type, the expression is converted as if by assignment362 to the return type of the function and the resulting value is returned to the caller.

362) Assignment removes any extra range and precision.

...

Code Block
bgColor#ccccff
langc
float calcPercentage(float value) {
  return (float)(value * 0.1f);
}

void floatRoutine(void) {
  float value = 99.0f;
  long double percentage;

  percentage = calcPercentage(value);
}

Compliant

...

Solution (Alternative)

Unfortunately, not all compilers honor casts. In this case, the range and precision must be forced by assignment to a variable of the correct type. This compliant solution forces the assignment by type-qualifying result as volatile and assigning the result of the floating-point operation to result before returning it:

...

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

...