Simpler method to detect int overflow...
The two simplest methods I know are:
SafeInt was written by David LeBlanc, and Microsoft uses it.
safe_iop was written by ???, and Android uses it.
The next simplest method is to use a compiler intrinsic. Unfortunately, I have not seen many of them. I believe I saw some for GCC recently.
The neat thing about intrinsics are (1) they provide a familiar C function call and (2) they are not bound by the Undefined Behavior you are trying to avoid. That means an instrinsic can perform the addition and the program will still be well defined, even it it overflows.
(In C/C++, if you perform the addition and it overflows, then the program is illegal. You are not allowed to perform the operation and then check the result).
The next simplest method is assembly and inline assembly. Again, its not bound by the Undefined Behavior you are trying to avoid in C/C++.
Assembly and inline assembly routines are the method I use. I work on mobile platforms and I have a library for i686, x86_64, ARM and MIPS.
I learned a long time ago its a pain in the butt to try and do this cross-platform in a well defined, portable and efficient manner from C, especially for some operations.
I was constantly checking results of compilations and starring at disassembled code to make sure the code generation was good. So I abandoned portable in the name of simplicity and efficiency.
Also see How to detect integer overflow in C/C++? on Stack Overflow.
floatcan represent is
1.0 / 10000would result in a value of
0.0because the actual value is too small. \$\endgroup\$