0

I want to check under what circumstance will overflow_error and underflow_error exception be generated in c++, so I wrote a demo to try to generate overflow_error exception, but failed:

#include <iostream>
#include <stdexcept>
using std::cout; using std::endl;
int main() {
    try {
        int a = std::pow(2, 31) - 1;
        cout << a << endl;
        int b = 1;
        int c = a + b;
        cout << c << endl;
    } catch (std::overflow_error ex) {
        cout << ex.what() << endl;
    }
    return 0;
}

The out put is:

2147483647
-2147483648

As you can see, no overflow_error exception generated, so, my questions are what the arithmetic overflow errors and arithmetic underflow errors are and how to generate overflow_error and underflow_error exception in c++?

3

1 Answer 1

2

The only standard library components that throw std::overflow_error are std::bitset::to_ulong and std::bitset::to_ullong.

The standard library components do not throw std::underflow_error (mathematical functions report underflow errors as specified in math_errhandling).

In your example, you are trying to check signed integer overflow. You need to specify flag for this check.

For example:

Use clang++ to compile and link your program with -fsanitize=undefined flag.

% cat test.cc
int main(int argc, char **argv) {
  int k = 0x7fffffff;
  k += argc;
  return 0;
}
% clang++ -fsanitize=undefined test.cc
% ./a.out

test.cc:3:5: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'

Sign up to request clarification or add additional context in comments.

1 Comment

Note that the flag is compiler-specific.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.