I am learning C ++, I was trying to write this function to find the largest fibonacci integer that can fit into an integer type:
void findFibThatFitsInAnInt() { int n1 = 1; int n2 = 1; int fib = 0; try { while ( true ) { fib = n1 + n2; n1 = n2; n2 = fib; cout << "Fibonacci number : " << fib << "\n"; } } catch (overflow_error & e) { cout << "The largest fib that can fit into an int is : " << fib << "\n"; cout << e.what() << "\n"; } cout << "The largest fib that can fit into an int is : " << n1 << "\n"; }
But the fact is that overflow_error is not caught at all. I know other ways to do this:
I know that I can write like:
while ( fib >= 0 ) { fib = n1 + n2; n1 = n2; n2 = fib; cout << "Fibonacci number : " << fib << "\n"; }
and because fib is just "int" and not an unsigned int, it will eventually become <0 (oddly enough) when it is assigned a value that exceeds the capacity of type int.
Question: overflow_error for such a bandwidth issue detected at runtime in C ++? Didn't I understand something about overflow_error? This is what I know from my google foo:
Defines the type of object to be excluded. It can be used for arithmetic errors of report overflow (that is, situations when the result of the calculation is too large for the target type)
If overflow_error is ignored for whole overflows, is there a way to enable it for my C ++ compiler (visual studio 2013?)
source share