Excerpt |
---|
When we implement add function by operator + |
...
in C++, sometimes we face over error - actually system does not show any error and that should be continuously increased, but there is a possibility to change into minus value suddenly. |
You can see the same case when you compile and run by below code:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <iostream> using namespace std; int main() { int a; for(int b=0; b<1000000; b++) { cout << a << "\n"; a+= 10000000;#include<stdio.h> #include<limits.h> #include<stdlib.h> int addOvf(int* result, int a, int b) { if( a > INT_MAX - b) return -1; else { *result = a + b; return 0; } } |
Below safe_add() function enables you to check overflow error:
Code Block | ||||
---|---|---|---|---|
| ||||
#define INT_MAX } } int main() { int *res = (int *)malloc(sizeof(int)); int x = 2147483640; int y = 10; printf("%d", addOvf(res, x, y)); printf("\n %d", *res); getchar(); return 0; } 2147483647 #define INT_MIN -2147483648 int safe_add(int &sum, int a, int b) { if (abs(a)>INT_MAX-abs(b)) { cout << "overflow : " << a << "+" << b << endl; return 0; } sum = a + b; return 1; } |
Time Complexity : O(1)
Space Complexity: O(1)