Tim Tim - 1 year ago 188
C++ Question

How to detect an overflow in C++?

I just wonder if there is some convenient way to detect if overflow happens to any variable of any default data type used in a C++ program during runtime? By convenient, I mean no need to write code to follow each variable if it is in the range of its data type every time its value changes. Or if it is impossible to achieve this, how would you do?

For example,

float f1=FLT_MAX+1;
cout << f1 << endl;

doesn't give any error or warning in either compilation with "gcc -W -Wall" or running.

Thanks and regards!

Answer Source

Consider using boosts numeric conversion which gives you negative_overflow and positive_overflow exceptions (examples).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download