Versions Compared

Key

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

...

Section 6.8.6.4, para. 2, of the C standard [ISO/IEC 9899:2011] 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.

...

NOTE: WG14 voted to include the following text in C11 [ISO/IEC 9899:2011]. It impacts only implementations that implement the optional Annex F, "IEC 60559 floating-point arithmetic."

...

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 5.2.4.2.2, para. 8, 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);
}

...

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

Related Guidelines

 ISO/IEC 9899:2011, Section 6.8.6.4, "The return statement"

...