Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,973 questions

51,917 answers

573 users

How to add two int number safely without overflow in C

1 Answer

0 votes
#include <stdio.h>
#include <limits.h>

int add_safe(int a, int b) {
    if (a > 0 && b > INT_MAX - a) {
        puts("overflow+");
        return -1;
    } else if (a < 0 && b < INT_MIN - a) {
        puts("overflow-");
        return -1;
    }
    return a + b;
}

int main(void) {
    int a = 2147483647, b = 10;
 
    printf("%d\n", add_safe(a, b));
    
    a = -10; b = -2147483648;
    printf("%d\n", add_safe(a, b));
    
    a = 83472, b = 93821;
    printf("%d\n", add_safe(a, b));

    return 0;
}



/*
run:

overflow+
-1
overflow-
-1
177293

*/

 



answered Jan 4, 2021 by avibootz
...