Main content: Detection of two integral type addition whether overflow
#include <stdio.h> #include <limits.h>int main (int argc, char *argv[]) {/* * A and B are nonnegative integer variables to detect if a+b will "overflow" * ///int_max=2147483647 INT a=123456789,b=2147483000; /* Method One: if (a+b < 0) printf ("overflow\n"); Cause of error: On some machines, the addition operation sets the internal register to four positive, negative, 0, and overflow. On this machine the C compiler has reason to detect, A and B add, and then check the internal register of the correlation flag is negative, but when the overflow occurs, the internal register state is overflow instead of negative, then overflow detection will fail/ //* The correct method is: Law one, Both A and B are coerced into unsigned integers; (reason: Because if you do not turn the words two number, if the addition result is greater than int_max words in the 32 register is signed, the sign bit is set 1, become negative, so it is impossible to more than Int_max, that is, detection is not out) * /#if 1 if ((unsigned) A + (unsigned) b > Int_max)//(unsigned) is required, Int_max is defined in limits.h, if not, implement {//Int_max =2147483647 printf ("overflow\n"); } #else/* Method II, */if (a > Int_max-b) //write this form can be used (unsigned) {printf ("overflow\n");} #endif return 0;}
Output:
Program Ape's---C language details 7