Skip to content

Chapter 2 p73 #10

@SneedusSnake

Description

@SneedusSnake

Current implementation of saturating_add:
return (-neg & INT_MIN) + (-pos & INT_MAX)

always returns either INT_MAX or INT_MIN, even when there is no overflow.

Proposed solution:

return (-neg & INT_MIN) + (-pos & INT_MAX) + (~(-(neg + pos)) & sum);

Plus some assertions:

    assert(saturating_add(1,2) == 3);
    assert(saturating_add(-1,2) == 1);
    assert(saturating_add(-1,-2) == -3);
    assert(saturating_add(500, 600) == 500 + 600);
    assert(saturating_add(2839902, 88888888) == 2839902 + 88888888);
    assert(saturating_add(INT_MAX-5, 6) == INT_MAX);
    assert(saturating_add(INT_MIN+3, -6) == INT_MIN);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions