addu

Add two unsigned integers, checking for overflow (aka carry).

The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end.

  1. uint addu(uint x, uint y, bool overflow)
  2. ulong addu(ulong x, ulong y, bool overflow)
  3. ucent addu(ucent x, ucent y, bool overflow)
    nothrow @safe @nogc pure pragma(inline, true)
    static if(is(ucent))
    ucent
    addu
    ()
    (
    ucent x
    ,
    ucent y
    ,
    ref bool overflow
    )

Parameters

x ucent

left operand

y ucent

right operand

overflow bool

set if an overflow occurs, is not affected otherwise

Return Value

Type: ucent

the sum

Examples

for (uint i = 0; i < 10; ++i)
{
    bool overflow;
    immutable uint r = addu (uint.max - i, uint.max - i, overflow);
    assert (r == 2 * (uint.max - i));
    assert (overflow);
}

bool overflow;
assert(addu(2, 3, overflow) == 5);
assert(!overflow);

assert(addu(1, uint.max - 1, overflow) == uint.max);
assert(!overflow);

assert(addu(uint.min, -1, overflow) == uint.max);
assert(!overflow);

assert(addu(uint.max, 1, overflow) == uint.min);
assert(overflow);

overflow = false;
assert(addu(uint.min + 1, -1, overflow) == uint.min);
assert(overflow);

assert(addu(0, 0, overflow) == 0);
assert(overflow);                   // sticky
bool overflow;
assert(addu(2L, 3L, overflow) == 5);
assert(!overflow);

assert(addu(1, ulong.max - 1, overflow) == ulong.max);
assert(!overflow);

assert(addu(ulong.min, -1L, overflow) == ulong.max);
assert(!overflow);

assert(addu(ulong.max, 1, overflow) == ulong.min);
assert(overflow);

overflow = false;
assert(addu(ulong.min + 1, -1L, overflow) == ulong.min);
assert(overflow);

assert(addu(0L, 0L, overflow) == 0);
assert(overflow);                   // sticky

Meta