Versions Compared

Key

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

...

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;
    }

...