In response to the SO question C: f>0 vs Perl: $f>0?, the use of overflow to terminate the loop is referred to as "poor programming practice". Paraphrased:
Your c code is actually exiting because of poor programming practice. You're relying on
fib
being along long int
, which has an upper limit of 9.22337204 × 10^18. When you loop around to the 93rd iterationfib
becomes 1.22001604 × 10^19, which overflows and becomes negative.
Substantially the same code:
cat >fib.c <<EOF
#include <stdio.h>
int main(){
for (long long int temp, i=1, prev=0, fib=1; fib>0 ; i++, temp=fib, fib+=prev, prev=temp)
printf("%lli: %lli\n", i, fib);
}
EOF
gcc -std=c99 -ofib fib.c
./fib
The code was intended to be a one time "throw-away" program which was evidenced by the use of single letter variable names in the original version. The use of the overflow being indicated by fib
becoming negate was used to terminate the loop.
Without knowing in advance what the maximum number of iterations the hardware architecture could handle what would be good "programming practice" to terminate the loop knowing that long long int
is limited yet desiring as many values as possible?
LLONG_MAX
orULLONG_MAX
from<<limits.h>
. \$\endgroup\$ – D.Q. Feb 8 '12 at 12:14