Versions Compared

Key

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

To ensure predictable program execution casts to type float must be present on all floating-point function calls.

Wiki Markup
The C99 standard \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] states in Section 6.8.6.4, Paragraph 3
states
,

If a return statement with an expression is executed, the value of the expression is returned to the caller as the value of the function call expression. If the expression has a type different from the return type of the function in which it appears, the value is converted as if by assignment to an object having the return type of the function. 142)

...

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

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

  percentage = calcPercentage(value);
}

Compliant Code Example (Alternate)

Unfortunately, not all compilers may honor casts.  In this case the range and precision must be forced by assignment to a variable of the correct type.  The following code example illustrates this approach.

Code Block
bgColor#ccccff

float calcPercentage(float value) {
  volatile float result;

  result = value * 0.1f;

  return result;
}

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

  percentage = calcPercentage(value);
}

Risk Assessment

Failure to follow this guideline can lead to inconsistent results across different platforms.

...

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.htm]\]