CXX.INT_TO_FLOAT.CONV

Use of implicit conversion in an arithmetic operation

This checker reports a defect when the code tries to implicitly convert integers to a floating-point format for floating-point operations.

Vulnerability and risk

Using integer arithmetic to calculate a value for assignment to a floating-point variable may lead to the loss of information.

Mitigation and prevention

You can avoid this issue by converting one of the integers in the expression to a floating type.

Vulnerable code example 1

1  void func(void) {
2  short a = 533;
3  int b = 6789;
4  long c = 466438237;
5  float d = a / 7; /* d is 76.0 */
6  double e = b / 30; /* e is 226.0 */
7  double f = c * 789; /* f may be negative due to overflow */
8  }

In this non-compliant code example, the division and multiplication operations take place on integers and are then converted to a floating-point values. Consequently, 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. The results are truncated to the nearest integer or may overflow.

Klocwork reports a CXX.INT_TO_FLOAT.CONV defect at lines 5, 6 and 7 indicating: “Conversion of integral type to floating type may result in loss of information.”

Fixed code example 1

1  void func(void) {
2  short a = 533;
3 int b = 6789;
4  long c = 466438237;
5  float d = a / 7.0f; /* d is 76.0 */
6  double e = b / 30.0; /* e is 226.0 */
7  double f = (double)c * 789; /* f may be negative due to overflow */
8  }

In the fixed example, Klocwork no longer reports a defect because the decimal error in initialization is eliminated by ensuring that at least one of the operands to the division operation is floating-point.

Vulnerable code example 2

1  void func(void) {
2  short a = 533;
3  
4  float d;
5  d = a / 7; /* d is 76.0 */
6  }

In this example, the division operation takes place on integers that are then converted to floating-point values. Consequently, floating-point variable d is not initialized correctly, because the operations take place before the values are converted to floating-point values.

Klocwork reports a CXX.INT_TO_FLOAT.CONV defect at line 5, indicating, “Conversion of integral type to floating type may result in loss of information.”

Fixed code example 2

1  void func(void) {
2  short a = 533;
3  
4  float d = a;
5  
6  d /= 7; /* d is 76.14286 */
7  }

In this example, Klocwork no longer reports a defect because 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.