Re:Fast integer overflow detection (2012)
by Someone on Monday December 15, 2014 @03:23AM
(#8751094)
But you want
if( !canSafelyAdd(a,b)) return ERROR;
c = a + b;
To compile down to an add and a check of the overflow bit. For that, you need help from the compiler.There are many examples where compilers special-case what is in a library. For example, compilers know they do not have to call strlen every time through this loop:
for(int i = 0; i < strlen(s); ++i)The enough help you need is, in the implementation of the library function #if X86 #if GCC etc and then the assembly for each case, otherwise the slow but standard implementation. And that's one file, the code never to be directly used but by function name. It's already done this way in the current libraries for a lot processor specific stuff.
It's: write one header with a few #if's once, everybody use it, whenever she needs it.
You'd just call
and be sure that on the common platform it's optimal thanks to the #if's in the header, and not write every time you'd want to check if the addition would be safe.