Versions Compared

Key

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

...

In addition, because floating-point numbers can represent large values, programmers often mistakenly assume that they can represent all digits of those values. To gain a large dynamic range, floating-point numbers maintain a fixed number of bits of precision and an exponent. Incrementing a large floating-point value might not change that value within the available precision.

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

...

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

...

Because 0.1f is rounded to the nearest representable 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.

...

Automated detection of floating-point loop counters is straightforward.

Related

...

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

Related Guidelines

C Secure Coding Standard: "FLP30-C. Do not use floating point variables as loop counters"

C++ Secure Coding Standard: "FLP30-CPP. Do not use floating point variables as loop counters"

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup

...

" ac:schema-version="1" ac:macro-id="c9bc39f9-412a-40b4-a51f-e5d0f89b1e9e"><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="b40fca3b-badd-438f-ad96-b367153e258f"><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>

...

NUM11-J. Check floating-point inputs for exceptional values      03. Numeric Types and Operations (NUM)      NUM13-J. Do not construct BigDecimal objects from floating-point literals