...
Subclause 6.8.6.4, paragraph 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.
...
Conversion as if by assignment to the type of the function is required if the return expression has a different type than the function , but not if the return expression has a wider value only because of wide evaluation. This allows seemingly inconsistent and confusing behavior. Consider the following code as an example:
...
NOTE: WG14 voted to include the following text in the C Standard [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 subclause 5.2.4.2.2, paragraph 8, of the C Standard [ISO/IEC 9899:2011].
Code Block | ||||
---|---|---|---|---|
| ||||
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.
Bibliography
[ISO/IEC 9899:2011] | Subclause 6.8.6.4, "The return Statement"Annex F, "IEC 60559 Floating-Point Arithmetic" |
[WG14/N1396] |
...