Versions Compared

Key

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

...

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

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

  percentage = calcPercentage(value);
}

...

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

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

  percentage = calcPercentage(value);
}

...

Code Block
bgColor#ccccff
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);
}

Compliant Code Example (Outside the function 1)

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 example shows one way to force the correct range and precision in a situation in which the source of the called function can not be modified.  This is accomplished by casting the return value of the calcPercentage() function to float.

Code Block
bgColor#ccccff

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

  percentage = (float)calcPercentage(value);
}

Compliant Code Example (Outside the function 2)

This example shows another way to force the correct range and precision.  In this case a temporary variable is used as the forcing mechanism.

Code Block
bgColor#ccccff

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

  percentage = temp = calcPercentage(value);
}

Risk Assessment

...

Wiki Markup
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\]
\[[WG14/N1396|http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1396.htmAA. C References#WG14/N1396]\]