If a floating-point value is to be demoted to a floating-point value of a smaller range and precision or to an integer type, or if an integer type is to be converted to a floating-point type, the value must be represented in the new type.
Section 6.3.1.4 of the C standard Standard [ISO/IEC 9899:2011] says:,
When a finite value of real floating type is converted to an integer type other than
_Bool
, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.When a value of integer type is converted to a real floating type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. If the value being converted is outside the range of values that can be represented, the behavior is undefined.
...
See also undefined behaviors 17 and 18 in Annex J of the C standardStandard.
Consequently, in implementations that do not allow for the representation of all numbers, conversions of numbers between zero and FLT_MIN
may result in undefined behavior.
...
Tool | Version | Checker | Description | Fortify SCA | V. 5.0 |
| Can detect violations of this rule with CERT C Rule Pack.|||
---|---|---|---|---|---|---|---|---|---|
Compass/ROSE |
|
| Can detect some violations of this rule. However, it does not flag implicit casts, only explicit ones. | ||||||
| MISRA_CAST | Can detect instances where implicit float conversion is involved: implicitly converting a complex expression with integer type to floating type, implicitly converting a double expression to narrower float type (may lose precision), implicitly converting a complex expression from | |||||||
Fortify SCA | 5.0 |
| Can detect violations of this rule with CERT C Rule Pack. | ||||||
PRQA QA-C |
| 4450 | Partially implemented. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
...
ISO/IEC 9899:2011 Section 6.3.1.4, "Real floating and integer," and Section 6.3.1.5, "Real floating types"
...
...
...
NUM12-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data | |
ISO/IEC TR 24772 | Numeric conversion errors [FLC] |
MITRE CWE |
...
...
Incorrect conversion between numeric types |
...
Bibliography
[IEEE 754] | IEEE 754-1985 Standard for Binary Floating-Point Arithmetic |
[ISO/IEC 9899:2011] | Section 6.3.1.4, "Real Floating and Integer" Section 6.3.1.5, "Real Floating Types" |
...