FloatLoopCounter
Go Up to C++ Audits
Contents
Description
FloatLoopCounter warns on using a floating point value as a loop counter. (CERT:FLP30-C, FLP30-CPP).
According to rules on Floating Point numbers, FLP30-C: Do not use floating-point variables as loop counters.
Different implementations have different precision limitations, and to keep code portable, floating-point variables should not be used as loop counters.
Incorrect
In this code example, a floating-point variable is used as a loop counter. The result of the iteration is 9.
void __fastcall TForm1::func(void)
{
int Iterations;
Iterations = 0;
for (float x = 0.1f; x <= 1.0f; x += 0.1f)
{
/* Loop may iterate 9 or 10 times */
Iterations = Iterations + 1;
}
ShowMessage("The number of iterations is" +UnicodeString(Iterations);
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
func();
}
Correct
In this code example, an integer variable is used as a loop counter. The result of the iteration is 10.
void __fastcall TForm1::func(void)
{
int Iterations;
Iterations = 0;
for (int x = 1; x <= 10; x += 1)
{
/* Loop iterates 10 times */
Iterations = Iterations + 1;
}
ShowMessage("The number of iterations is" +UnicodeString(Iterations);
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
func();
}