Using integer arithmetic to calculate a value for assignment to a floating-point variable may lead to loss of information. This problem can be avoided by converting one of the integers in the expression to a floating type.
When converting integers to floating-point values, and vice versa, it is important to carry out proper range checks to avoid undefined behavior (see FLP34-C. Ensure that floating-point conversions are within range of the new type).
Noncompliant Code Example
In this noncompliant code example, the division and multiplication operations take place on integers and are then converted to floating point. Consequently, floating-point variables
f are not initialized correctly because the operations take place before the values are converted to floating-point values. The results are truncated to the nearest integer or may overflow.
Compliant Solution (Floating-Point Literal)
In this compliant solution, the decimal error in initialization is eliminated by ensuring that at least one of the operands to the division operation is floating point:
Compliant Solution (Conversion)
In this compliant solution, the decimal error in initialization is eliminated by first storing the integer in the floating-point variable and then performing the arithmetic operation. This practice ensures that at least one of the operands is a floating-point number and that the subsequent arithmetic operation is performed on floating-point operands.
FLP06-C-EX0: It may be desirable to have the operation take place as integers before the conversion (obviating the need for a call to
trunc(), for example). If this is the programmer's intention, it should be clearly documented to help future maintainers understand that this behavior is intentional.
Improper conversions between integers and floating-point values may yield unexpected results, especially loss of precision. Additionally, these unexpected results may actually involve overflow, or undefined behavior.
|Supported: This rule aims to prevent truncations and overflows. All possible overflows are reported by Astrée.|
|Axivion Bauhaus Suite|
|LANG.TYPE.MOT||Mismatched operand types|
Can detect violations of this rule. Any assignment operation where the type of the assigned-to value is
|LDRA tool suite|
Implicit conversions from integral to floating type which may result in a loss of information shall not be used
|Polyspace Bug Finder|
Overflow from operation between floating points
The value of an expression shall not be assigned to an object with a narrower essential type or of a different essential type category
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
|[Hatton 1995]||Section 2.7.3, "Floating-Point Misbehavior"|