0

The C++ Standard at some point states that:

5 Expressions [expr]
...
If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows...]

I'm trying to understand why most(all?) implementations choose to ignore overflows rather than doing something like throwing an std::overflow_error exception. Is it not to incur any additional runtime cost? If that's the case, can't the underlying arithmetic processing hardware be used to do that check for free?

4
  • 2
    Too expensive to test for overflow on int operation. Coders can always test when operations may produce overflow and one doesn't want to penalize all the other operations where they don't occur. Commented Jan 10, 2022 at 15:29
  • Hardware has no idea that you're currently running compiled C++ code, you'd need to add the checks manually to every single arithmetic operation which would blow up executable size to unreasonable size. Commented Jan 10, 2022 at 15:31
  • 1
    Consider the following live demo: godbolt.org/z/PhY5zq31E. Note the generated assembly, which is pretty minimal. Overflow checking would require additional instructions. Moreover, the LEA instruction does not set flags. Commented Jan 10, 2022 at 15:32
  • 2
    Is it not to incur any additional runtime cost? Yes. can't the underlying arithmetic processing hardware be used to do that check for free? Nope. Commented Jan 10, 2022 at 15:33

1 Answer 1

3

If that's the case, can't the underlying arithmetic processing hardware be used to do that check for free?

Raising an exception always has a cost. But perhaps some architectures can guarantee that when an exception is not raised, then the check is free.

However, C++ is designed to be efficiently implementable on a wide range of architectures. It would violate the design principles of C++ to mandate checking for integer overflow, unless all architectures could support such checks with zero cost in all cases where overflow does not occur. This is not the case.

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

1 Comment

Thanks for clarifying.

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.