#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
bool addingWillOverflow(int x, int y) {
return ((x > 0) && (y > INT_MAX - x)) ||
((x < 0) && (y < INT_MIN - x));
}
bool willAdditionOverflowUnsigned(unsigned int x, unsigned int y) {
return (x > UINT_MAX - y);
}
// Some compilers, like GCC or Clang, provide built-in functions to detect overflow
bool willAdditionOverflowBuiltin(int a, int b) {
int result;
return __builtin_add_overflow(a, b, &result);
}
int main() {
int x = 38839299, y = 2372783642;
printf("%s\n", addingWillOverflow(x, y) ? "true" : "false");
x = 2438839299;
y = 3972783642;
printf("%s\n", addingWillOverflow(x, y) ? "true" : "false");
unsigned int x1 = 138839299, y1 = 2372783642;
printf("%s\n", willAdditionOverflowUnsigned(x1, y1) ? "true" : "false");
x1 = 4238839299;
y1 = 2372783642;
printf("%s\n", willAdditionOverflowUnsigned(x1, y1) ? "true" : "false");
printf("%s\n", willAdditionOverflowBuiltin(x, y) ? "true" : "false");
return 0;
}
/*
run:
false
true
false
true
true
*/