...
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,
Code Block |
---|
float f(float x) { return x * 0.1f; } float g(float x) { return x * 0.1; } |
...
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.
Noncompliant Code Example
The following example code has been constructed to illustrate an example that does not conform to this recommendation. The code is non-conforming because it does not cast the result of the expression in the return statement and thereby guarantee the range or precision is no wider than expected. The uncertainty in this example is introduced by the constant 0.1. This constant may be stored with a range or precision that is greater than that of float. Consequently, the result of x * 0.1 may also have a range or precision greater than that of float. As described above, this range or precision may not be reduced to that of a float and, thus, the caller of g() may have a value that is more precise than expected. This may lead to inconsistent program execution across different platforms.
Code Block | ||
---|---|---|
| ||
float g(float x) {
 return x * 0.1;
}
|
Compliant Code Example
The following code example remedies the above noncompliant code by casting the value of the expression in the return statement. This forces the return value to have the expected range and precision as described in Section 5.2.4.2.2 9 of the C Standard.
Code Block | ||
---|---|---|
| ||
float g(float x) {
 return (float)(x * 0.1);
}
|
Risk Assessment
Failure to follow this guideline can lead to inconsistent results across different platforms.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FLP37-C | low | unlikely | medium | P2 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.