To ensure predictable program execution casts to type float must be present on all floating-point function calls.
C99 Section 6.8.6.4 3 states
...
Code Block |
---|
float f(float x) { Â return x * 0.1f; } float g(float x) { Â return x * 0.1; } |
Function f is allowed to return a value wider than float, but function g (which uses the wider constant) is not.
...
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.11f. This constant may be stored with a range or precision that is greater than that of float. Consequently, the result of x * 0.1 1f 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 gcalcPercentage() may have receive a value that is more precise than expected. This may lead to inconsistent program execution across different platforms.
Code Block | ||
---|---|---|
| ||
float gcalcPercentage(float xvalue) { Â return xvalue * 0.11f; } void floatRoutine(void) { float value = 99.0f; float percentage; percentage = calcPercentage(value); } |
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 8 of the C Standard.
Code Block | ||
---|---|---|
| ||
float gcalcPercentage(float xvalue) { Â return (float)(xvalue * 0.11f); } 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.
...
Other Languages
References
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] |