The following snippet of C++ code computes Fibonacci numbers. With 32-bit integers, we overflow when n=47
and b
becomes negative.
int a=0, b=1, n=2;
do {
a += b; int c = a; a = b; b = c;
++n;
} while ( b>0 and n<50 );
std::cout << "Ended at n=" << n << " b=" << b << std::endl;
Compiling on g++ 4.9.1 all is well; unless I use -O2
or -O3
in which case the loop runs until n=50
. Is the compiler perhaps assuming that, as a
and b
start out positive and only additions are applied, they must stay positive? A look at the assembly output confirms that the condition b>0
isn't even being checked.
Same happens for g++ 4.7.0. So I suspect this is deliberate behaviour...?