Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Conversion from integer types such as char, short, int and long to floating types such as float and double point in an assignment statement may lead to loss of information if one of the integer types is not converted to a floating type.

...

In this non-compliant code, the floating point variables d, e and f are not initialized correctly because the operations take place before the values are converted to floating point values and hence the results are truncated to the nearest decimal point or may overflow. Consequently, the division and multiplication operations take place on integers then get converted to floating point.

Code Block
bgColor#FFCCCC
short a = 533;
int b = 6789;
long c = 466438237;

float d = a / 7; /* d is 76.0 */
double e = b / 30; /* e is 226.0 */
double f = c * 789; /*  f may be negative due to overflow */

Compliant

...

Solution 1

In this compliant codesolution, we remove the decimal error in initialization by making the division operation to involve is eliminated by ensuring that at least one floating point operand. Hence, the result of the operation is the correct floating point numberof the operands to the division operation is floating point.

Code Block
bgColor#CCCCFF
short a = 533;
int b = 6789;
long c = 466438237;

float d = a / 7.0f; /* d is 76.14286 */
double e = b / 30.; /* e is 226.3 */
double f = (double)c * 789; /* f is 360*/

Compliant

...

Solution 2

In this compliant code, we remove the decimal error in initialization by first storing the integer in the floating point variable and then performing the division operation. This ensures that atleast at least one of the operands is a floating point number and hence, consequently the result operation is the correct performed on floating point numbernumbers.

Code Block
bgColor#CCCCFF
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 591176.47275 */

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Hatton 95|AA. C References#Hatton 95]\] Section 2.7.3, "Floating-point misbehavior"


\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 5.2.4.2.2, "Characteristics of floating types <float.h>"