Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.


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:

...

Below safe_add() function enables you to check overflow error:

Code Block
languagecpp
titlesafe_add.cpp
#define INT_MAX 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;
    }

...