Versions Compared

Key

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

...

As a result, floating-point variables must not be used as loop counters.

Noncompliant Code Example

This noncompliant code example uses a floating-point variable as a loop counter. The decimal number 0.1 cannot be precisely represented as a float or even as a double.

...

Because 0.1f is rounded to the nearest value that can be represented in the value set of the float type, the actual quantity added to x on each iteration is somewhat larger than 0.1; consequently, the loop executes only nine times and fails to produce the expected output.

Compliant Solution

This compliant solution uses an integer loop counter from which the desired floating-point value is derived.

Code Block
bgColor#ccccff
for (int count = 1; count <= 10; count += 1) {
  float x = count/10.0f;
  System.out.println(x);
}

Noncompliant Code Example

This noncompliant code example uses a floating-point loop counter that is incremented by an amount that is too small to change its value given the precision.

...

The code loops forever on execution.

Compliant Solution

This compliant solution uses an integer loop counter from which the floating-point value is derived. Additionally, it uses a double to ensure that the available precision suffices to represent the desired values.

Code Block
bgColor#ccccff
for (int count = 1; count <= 10; count += 1) {
  double x = 100000000.0 + count;
  /* ... */
}

Risk Assessment

Using floating-point loop counters can lead to unexpected behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

NUM12-J

low

probable

low

P6

L2

Automated Detection

Automated detection of floating-point loop counters is straightforward.

Related Guidelines

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="682b3c69f8c5004b-2cbcf94b-45c74cb7-b29bbc6a-78f1100a89901f471613a404"><ac:plain-text-body><![CDATA[

[[Bloch 2005

AA. Bibliography#Bloch 05]]

Puzzle 34: Down for the Count

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="428ddd0d9e671f67-a77d0655-43fe438d-9cae96d8-0136492058f905e666e46747"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[§4.2.3, "Floating-Point Types, Formats, and Values"

http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3]

]]></ac:plain-text-body></ac:structured-macro>

...