There are two kinds of integer arithmetic operations in C language, symbolic operation and unsigned operation. In the unsigned operation, there is no sign bit, so there is no overflow concept.
All unsigned operations are modeled on the N-second side of 2. If one operand of an arithmetic operator is a signed book and the other is an unsigned number, then a signed number
will be converted to unsigned numbers (representing a small range that is always converted to a large range), and the overflow will not occur. However, when two operands are signed
, an overflow can occur. And the result of the overflow is undefined. When the result of an operation overflows, any assumption is unsafe.
For example, assuming that A and B are two nonnegative integer variables (signed), we need to check whether a+b overflows, a way to take it for granted:
if (A + B < 0)
Overflow
In fact, in the real world, this is not going to work. When A+b does overflow, all assumptions about the outcome are unreliable. For example, in some
The CPU of the machine, the addition operation will set an internal register of four states: positive, negative, 0 and overflow. On this machine, the C compiler has every reason to achieve the above
example, so that a+b return is not a negative, but the memory register overflow state. Obviously, the judgment of if will fail.
A correct way is to cast both A and B to unsigned integers:
if ((unsigned) A + (unsigned) b > Int_max)
Overflow
The Int_max value here is the maximum value for the signed integral type. is a predefined constant in the general compiler. ANSI c defines the Int_max in the limits, and the value is
2 of the 31-time square-1.
Another possible way to not use unsigned arithmetic is to:
if (A > Int_max-b)
Overflow
PS: The highest bit (31 digits) of the signed number is the sign bit, the highest bit is 0, when the positive, 1 is the time to represent the negative. operation, the sign bit does not participate in the operation, but if two numbers are added and 30 bits need to enter 1 o'clock, then the overflow is represented.