Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: wordsmithing

...

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

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

  percentage = calcPercentage(value);
}

Compliant Solution (Cast)

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 subclause 5.2.4.2.2, paragraph 9, of the C Standard [ISO/IEC 9899:2011].

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);
}

Unfortunately, not all compilers honor casts. This compliant solution will only work on compilers that do honor casts.

Compliant Solution (Alternative)

Unfortunately, not all compilers For platforms that do not 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:

...