Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.
Method 1
There can be overflow only if signs of two numbers are same, and sign of sum is opposite to the signs of numbers.

1)  Calculate sum
2)  If both numbers are positive and sum is negative then return -1
     Else 
        If both numbers are negative and sum is positive then return -1
        Else return 0
[pastacode lang=”c” manual=”%23include%3Cstdio.h%3E%0A%23include%3Cstdlib.h%3E%0A%20%0A%2F*%20Takes%20pointer%20to%20result%20and%20two%20numbers%20as%0A%20%20%20%20arguments.%20If%20there%20is%20no%20overflow%2C%20the%20function%0A%20%20%20%20places%20the%20resultant%20%3D%20sum%20a%2Bb%20in%20%E2%80%9Cresult%E2%80%9D%20and%0A%20%20%20%20returns%200%2C%20otherwise%20it%20returns%20-1%20*%2F%0A%20int%20addOvf(int*%20result%2C%20int%20a%2C%20int%20b)%0A%20%7B%0A%20%20%20%20%20*result%20%3D%20a%20%2B%20b%3B%0A%20%20%20%20%20if(a%20%3E%200%20%26%26%20b%20%3E%200%20%26%26%20*result%20%3C%200)%0A%20%20%20%20%20%20%20%20%20return%20-1%3B%0A%20%20%20%20%20if(a%20%3C%200%20%26%26%20b%20%3C%200%20%26%26%20*result%20%3E%200)%0A%20%20%20%20%20%20%20%20%20return%20-1%3B%0A%20%20%20%20%20return%200%3B%0A%20%7D%0A%20%0A%20int%20main()%0A%20%7B%0A%20%20%20%20%20int%20*res%20%3D%20(int%20*)malloc(sizeof(int))%3B%0A%20%20%20%20%20int%20x%20%3D%202147483640%3B%0A%20%20%20%20%20int%20y%20%3D%2010%3B%0A%20%0A%20%20%20%20%20printf(%22%25d%22%2C%20addOvf(res%2C%20x%2C%20y))%3B%0A%20%0A%20%20%20%20%20printf(%22%5Cn%20%25d%22%2C%20*res)%3B%0A%20%20%20%20%20getchar()%3B%0A%20%20%20%20%20return%200%3B%0A%7D” message=”C Programming” highlight=”” provider=”manual”/]

Time Complexity : O(1)
Space Complexity: O(1)

[ad type=”banner”]

Method 2
Thanks to Himanshu Aggarwal for adding this method. This method doesn’t modify *result if there us an overflow.

[pastacode lang=”c” manual=”%23include%3Cstdio.h%3E%0A%23include%3Climits.h%3E%0A%23include%3Cstdlib.h%3E%0A%20%0Aint%20addOvf(int*%20result%2C%20int%20a%2C%20int%20b)%0A%7B%0A%20%20%20if(%20a%20%3E%20INT_MAX%20-%20b)%0A%20%20%20%20%20return%20-1%3B%0A%20%20%20else%0A%20%20%20%7B%0A%20%20%20%20%20*result%20%3D%20a%20%2B%20b%3B%0A%20%20%20%20%20%20return%200%3B%0A%20%20%20%7D%0A%7D%0A%20%0Aint%20main()%0A%7B%0A%20%20int%20*res%20%3D%20(int%20*)malloc(sizeof(int))%3B%0A%20%20int%20x%20%3D%202147483640%3B%0A%20%20int%20y%20%3D%2010%3B%0A%20%0A%20%20printf(%22%25d%22%2C%20addOvf(res%2C%20x%2C%20y))%3B%0A%20%20printf(%22%5Cn%20%25d%22%2C%20*res)%3B%0A%20%20getchar()%3B%0A%20%20return%200%3B%0A%7D” message=”C Programming” highlight=”” provider=”manual”/]

Time Complexity : O(1)
Space Complexity: O(1)

[ad type=”banner”]