c/c++ 에서 add(+) 에 대해 overflows 검사하는 법

Precondition. Addition of unsigned integers can result in an integer overﬂow

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

overﬂow. The tests in Table 5–5 are guaranteed not to overﬂow for appropriately signed values.

Postcondition. Another solution to detecting integer overﬂow is to perform

the addition and then evaluate the results of the operation. For example, to test

for overﬂow of signed integers, let sum = lhs + rhs. If lhs is non-negative and

sum < rhs, an overﬂow has occurred. Similarly, if lhs is negative and sum > rhs,

an overﬂow has occurred. In all other cases, the addition operation succeeds

without overﬂow. For unsigned integers, if the sum is smaller than either operand, an overﬂow has occurred.

## Reference

- http://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-c-c
- http://ptgmedia.pearsoncmg.com/images/0321335724/samplechapter/seacord_ch05.pdf
- http://stackoverflow.com/questions/1815367/multiplication-of-large-numbers-how-to-catch-overflow

## 댓글 없음:

## 댓글 쓰기