...
When converting integers to floating point and vice versa, it is important to carry out proper range checks in order to avoid undefined behavior (see FLP34-C. Ensure that floating point conversions are within range of the new type).
It may be desirable to have the operation take place as integers before the conversion (obviating the need for a trunc() call, for example). If that is done, it should be clearly documented to help future maintainers understand the intent of the code.
Non-Compliant Code Example
...
| Code Block | ||
|---|---|---|
| ||
short a = 533; int b = 6789; long c = 466438237; float d = a; double e = b; double f = c; d /= 7; /* d is 76.14286 */ e /= 30; /* e is 226.3 */ f *= 789; /* f is 368019768993.0 */ |
Risk Assessment
It may be desirable to have the operation take place as integers before the conversion (obviating the need for a trunc() call, for example). If that is done, it should be clearly documented to help future maintainers understand the intent of the codeImproper conversions between ints and floats may yield unexpected results, especially loss of precision. Additionally, these unexpected results may actually involve overflow, or undefined behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
FLP33-C | low | probable | low | P6 | L2 |
...