Versions Compared

Key

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

...

This compliant solution casts the value of the expression in the return statement. It forces the return value to have the expected range and precision, as described in Section section 5.2.4.2.2, para. 8paragraph 8, of the C Standard [ISO/IEC 9899:2011].

...

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.:

Code Block
bgColor#ccccff
langc
float calcPercentage(float value) {
  volatile float result;

  result = value * 0.1f;

  return result;
}

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

  percentage = calcPercentage(value);
}

...

Forcing the range and precision inside the calcPercentage() function is a good way to fix the problem once without having to apply fixes in multiple locations (every time calcPercentage() is called). However, access to the called function may not always be available. This compliant solution shows one way to force the correct range and precision in a situation in which the source of the called function cannot be modified. This behavior is accomplished by casting the return value of the calcPercentage() function to float.

...

[ISO/IEC 9899:2011]Section 6.8.6.4, "The return Statement"
Annex F, "IEC 60559 Floating-Point Arithmetic"
[WG14/N1396] 

 

...