Cast the return value of a function that returns a floating point type to ensure predictable program execution.
Section 6.8.6.4, para. paragraph 2, of the C standard Standard [ISO/IEC 9899:2011] states:
...
NOTE: WG14 voted to include the following text in C11 the C Standard [ISO/IEC 9899:2011]. It impacts only implementations that implement the optional Annex F, "IEC 60559 floatingFloating-point arithmeticPoint Arithmetic."
Require return expressions to be converted as if by assignment to the type of the function, but only in Annex F. This is a compromise that addresses the problems for Annex F implementations while not impacting non-Annex F implementations that exercise the license for wide returns.
Insert the following new subclause after F.5 (and increment subsequent subclause numbers):
F.6 The return statement
If the return expression is evaluated in a floating-point format different from the return type, then the expression is converted to the return type of the function and the resulting value is returned to the caller.
...
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 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); } |
...
Unfortunately, not all compilers 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.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
Bibliography
...
[ISO/IEC 9899:2011] | Section 6.8.6.4, "The return |
...
Statement" |
...
Annex F, "IEC 60559 Floating-Point Arithmetic" | |
[WG14/N1396] |