c/c++ 에서 add(+) 에 대해 overflows 검사하는 법
Precondition. Addition of unsigned integers can result in an integer overflow
if the sum of the left-hand side (LHS) and right-hand side (RHS) of an addition
operation is greater than UINT_MAX for addition of int type and ULLONG_MAX for
addition of unsigned long long type
Addition of signed integers is more complicated, as shown in Table 5–5.
As you test for these preconditions, make sure that the test itself does not
overflow. The tests in Table 5–5 are guaranteed not to overflow for appropriately signed values.Postcondition. Another solution to detecting integer overflow is to perform
the addition and then evaluate the results of the operation. For example, to test
for overflow of signed integers, let sum = lhs + rhs. If lhs is non-negative and
sum < rhs, an overflow has occurred. Similarly, if lhs is negative and sum > rhs,
an overflow has occurred. In all other cases, the addition operation succeeds
without overflow. For unsigned integers, if the sum is smaller than either operand, an overflow has occurred.
댓글 없음:
댓글 쓰기