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 thing is overflow_error is not caught at all. I know other ways of doing 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 an "int" not an unsigned int, it will eventually become < 0 ( strangely enough ) when it is assigned a value that is larger than the capacity of int type.
Question is : is overflow_error for this kind of capacity issue caught at runtime in C++? Did I misunderstand something about overflow_error? This is what I know from my google foo:
Defines a type of object to be thrown as exception. It can be used to report arithmetic overflow errors (that is, situations where a result of a computation is too large for the destination type)
If overflow_error is ignored for integer overflows is there a way to enable it for my c++ compiler ( visual studio 2013?)