How to check if integer addition will overflow in C

1 Answer

0 votes
#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

*/

 



answered May 17, 2025 by avibootz
edited May 17, 2025 by avibootz

Related questions

1 answer 143 views
1 answer 171 views
2 answers 168 views
1 answer 186 views
1 answer 169 views
1 answer 179 views
...