Home > Software design >  How to compare sum of two int64 with INT64_MAX?
How to compare sum of two int64 with INT64_MAX?

Time:12-03

I know number greater than INT64_MAX will wrap around negative, So how to compare when sum overflow, that is sum greater than INT64_MAX.

#include <iostream>

using namespace std;

int main() {
  int64_t a = INT64_MAX;
  int64_t b = 1;
  // cin >> a >> b;
  if (a   b <= INT64_MAX) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }
  return 0;
}

CodePudding user response:

First compare b to either INT64_MIN - a or INT64_MAX - a before the addition to prevent undefined behavior (UB) of signed integer overflow.

// True when sum overflows.
bool is_undefined_add64(int64_t a, int64_t b) {
  return (a < 0) ? (b < INT64_MIN - a) : (b > INT64_MAX - a);
}

Worst case: 2 compares.

For div, mul, sub

CodePudding user response:

Before compare, check a b to see if it will overflow.

int is_overflow(int64_t a, int64_t b) {
  if (((b > 0) && (a > (INT64_MAX - b))) ||
      ((b < 0) && (a < (INT64_MIN - b)))) {
    return 1;
  }
  return 0;
}
  • Related