Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect an overflow in C++?

Tags:

c++

gcc

overflow

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!

like image 412
Tim Avatar asked Dec 08 '22 06:12

Tim


1 Answers

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

like image 174
Georg Fritzsche Avatar answered Dec 11 '22 08:12

Georg Fritzsche