Auto overflow detection in C ++?

Possible duplicate:
Best way to detect integer overflow in C / C ++

Often, when I encoded something in C ++ using large numbers, I cannot say when the overflow occurs, even if I use something like a long or other 64-bit data type. Is there an effective way of detecting overflow than detecting erroneous values?

+6
source share
2 answers

There may not be so many that you could get from standard C ++:

5 expressions

4 If during the evaluation of an expression the result is not mathematically determined or not in the range of representable values ​​for its type, the behavior is undefined. [Note: most existing C ++ implementations ignore whole overflows. The treatment of dividing by zero, forming the remainder, using the zero divisor, and all floating point exceptions differ between machines and the library function is usually regulated. -end note]

It is best to use standard fixed fixed widths defined in <cstdint> , such as uint32_t .

Take a look at the <cerrno> header too for error codes like EOVERFLOW . There are overflow_error / underflow_error from <stdexcept> .

+2
source

In fact, you cannot even reliably detect overflow after the fact, because overflow in integer integer operations leads to undefined behavior. If the compiler can see that the code path is reached only in case of overflow, it allowed to optimize it completely (since in the case of undefined behavior it can do anything at all). Unsigned types are distinguished by the fact that they determined the characteristics of overflow (they perform arithmetic of the module).

Thus, the only way to detect overflow with signed types is to do an appropriate check in advance, which is quite expensive. It is almost always much more efficient to design such things so that the invariant of your algorithm ensures that there is no overflow.

As for resources for detecting possible overflow before it occurs, see https://stackoverflow.com/a/199413/445525

+1
source

Source: https://habr.com/ru/post/917259/


All Articles