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)
    nothrow @safe @nogc pure pragma(inline, true)
    ulong
    addu
    ()
    (
    ulong x
    ,
    ulong y
    ,
    ref bool overflow
    )
  3. ucent addu(ucent x, ucent y, bool overflow)

Parameters

x ulong

left operand

y ulong

right operand

overflow bool

set if an overflow occurs, is not affected otherwise

Return Value

Type: ulong

the sum

Examples

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
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

Meta