N
Noob
Ben said:[ Using a float as a loop index is not a good idea. ]
I emphatically agree.
An integer type is preferable. I don't think there is anything actually
wrong with the above as far as C is concerned (because of the guarantees
C makes about floating point arithmetic) but you'll make everyone read
the code several times just to be sure.
Considering that the condition (f == f+1) is true for (relatively) small
values of f, I would argue that using a float variable as a loop index
is a disaster waiting to happen.
#include <stdio.h>
void foo(unsigned long n)
{
float f;
for (f = 0; f < n; ++f)
{
float g = f+1;
if (f == g) break;
}
printf("f=%f n=%lu\n", f, n);
}
int main(void)
{
foo(10*1000*1000);
foo(20*1000*1000);
return 0;
}
$ gcc -Wall -Wextra tutu.c
$ ./a.out
f=10000000.000000 n=10000000
f=16777216.000000 n=20000000
Regards.