Versions Compared

Key

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

...

In this noncompliant code example, the division and multiplication operations take place on integers and are then converted to floating point. This causes floating-point variables d, e, and f to not be 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.

Code Block
bgColor#FFCCCC
langc
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 */

...

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.

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

...

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 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.

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

...