0

The following integer overflow detection function is given in Computer Systems: A Programmer's Perspective, 3e.

/* Determine whether arguments can be added without overflow */
int tadd_ok(int x, int y) {
    int sum = x+y;
    int neg_over = x < 0 && y < 0 && sum >= 0;
    int pos_over = x >= 0 && y >= 0 && sum < 0;
    return !neg_over && !pos_over;
}

The expression given for negative overflow matches the one given in the book.

The expression for positive overflow differs slightly. In the book, it says positive overflow can be detected if x > 0, y > 0, and sum <= 0. I'm wondering why the expression pos_over in the C function is different from this.

Thank you!

4
  • 5
    This algorithm makes sense at the level of pseudocode to teach you about two's complement arithmetic, but not as actual C code, because if the sum overflows then you have undefined behavior. Commented Jun 7, 2024 at 13:20
  • 1
    See "The ckd_ Checked Integer Operation Macros" in C23 p7.20.1. Commented Jun 7, 2024 at 13:22
  • 1
    Adding 0 cannot cause overflow. Commented Jun 7, 2024 at 13:23
  • As stark says, adding 0 cannot cause an overflow, and moreover you should be able to convince yourself that the sum of two positive values cannot overflow to 0. So it's a little sloppy for the description and the code to disagree, but they are equivalent. Commented Jun 7, 2024 at 13:26

1 Answer 1

3

Undefined behavior

The book is flawed.

The x+y; in int sum = x+y; may cause int overflow and the result of that is undefined behavior (UB). The rest of code is irrelevant and its logic is not supported by the C specification.

Code needs to test before the addition (or use a wider type).

Alternate (which returns the opposite truth-ness of OP's goal):

int is_undefined_add1(int a, int b) {
  return (a < 0) ? (b < INT_MIN - a) : (b > INT_MAX - a);
}

Tests for *, /, - at Test if arithmetic operation will cause undefined behavior.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.