One kind swap_int () will not be written because the overflow cause an error?

Like this:

void swap_int(int *a, int *b){
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}

When a + b exceeds int (signed) may represent a range, an overflow, an error will not exchange?

VS2013 && MinGW.org GCC-6.3.0-1 compiler test:

When a = 0x7FFFFFFF (INT_MAX), b = 0x7FFFFFFE, the sum will overflow, but the results displayed correctly. why?

We try 0x7FFFFFFF + 1, the result is -2147483648, i.e. negative minimum value; +2 obtain -2147483647; INT_MAX * 2 available -2; INT_MIN * 2 0 too. You can find out the law (at least in vs and gcc is this):

When overflow occurs, the result will appear at regular shown below:

 

即 INX_MAX + 1 = INX_MIN, INT_MIN 1 = INT_MAX.

Said switching function to see, when a + b will generate an overflow, then a, b will simultaneously [INT_MAX / 2, INT_MAX] simultaneously or in [INT_MIN, INT_MIN / 2].

I.e., the value of a + b is even overflow will not exceed 0, if a = INT_MAX, b = 2, then a = a + b = INT_MIN + 1 (the lower end away from the left in FIG most), b = ab = INT_MIN + 1 + (- b) = INT_MAX, adding two negative overflow again (from the lowest end in FIG right away), a = ab = INT_MIN + 1 + (- INX_MAX) = 2.

Therefore, even if the result of the addition overflow will not affect the results of the exchange.

 

Guess you like

Origin www.cnblogs.com/dabai56/p/10994770.html