Programmer --- C language details 7
Main Content: checks whether the sum of two integer types overflows.
# Include
# Include
Int main (int argc, char * argv []) {/** a and B are non-negative integer variables, check whether a + B will "overflow" * // INT_MAX = 2147483647 int a = 123456789, B = 2147483000;/* Method 1: if (a + B <0) printf ("overflow \ n"); error cause: On some machines, the addition operation sets the internal register to four States: positive, negative, zero and overflow. On this machine, the c compiler has a reason to detect this; a and B are added, and then check whether the internal register-related flag is negative. However, when overflow occurs, if the internal register status is overflow rather than negative, the overflow detection will fail. * // the correct method is method 1. Convert both a and B to unsigned integers; (cause: If no conversion is made, the two numbers are added. If the addition result is greater than INT_MAX, the two numbers are signed in 32 registers, and the sign bit is set to 1, which turns to a negative number, in this case, it cannot be greater than INT_MAX, that is, it cannot be detected.) */# if 1 if (unsigned) a + (unsigned) B> INT_MAX) // (unsigned) is indispensable, INT_MAX in limits. defined in h. If not, implement it by yourself {// INT_MAX = 2147483647 printf ("overflow \ n ");} # else/* method 2, */if (a> INT_MAX-B) // you do not need to write this form (unsigned) {printf ("overflow \ n ");} # endif return 0 ;}
Output: