As @EugeneSh. observes, the carry is either 0 or 1. Moreover, given that a
and b
both have the same unsigned type, their sum is well defined even if the arithmetic result exceeds the range of their type. Moreover, the (C) result of the sum will be less than both a
and b
when overflow occurs, and greater otherwise, so we can use the fact that C relational operations evaluate to either 0 or 1 to express the carry bit as
carry = (a + b) < a;
That does not require any headers, nor does it depend on a specific upper bound, or even on a
and b
having the same type. As long as both have unsigned types, it reports correctly on whether the sum overflows the wider of their types or unsigned int
(whichever is wider), which is the same as their sum setting the carry bit. As a bonus, it is expressed in terms of the sum itself, which I think makes it clear what's being tested.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…