You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

Floating point arithmetic is inexact and is subject to rounding errors. Consequently, floating point variables should not be used as loop counters.

Non-Compliant Code Example

In this non-compliant example, a floating point value has been used as a loop counter.

for (float count = 0.1f; count <= 1; count += 0.1f) {
  // ...
}

Implementation Specific Details

Under Microsoft Visual Express version 8.0 running on an x86 machine with Windows XP, this loop was executed only nine times.

Compliant Solution

In this compliant solution, the loop counter is an integer.

for (int count = 1; count <= 10; count += 1) {
  // ...
}

Risk Assessment

Using floating point loop counters could lead to unexpected behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FLP31-C

1 (low)

1 (unlikely)

3 (low)

P3

L3

References

[[ISO/IEC 14882-2003]] Sections 2.13.3, "Floating literals," and 3.9.1, "Fundamental types"
[[Lockheed Martin 05]] AV Rule 197, "Floating point variables shall not be used as loop counters."

  • No labels