I need to catch overflow int without resorting to math.
But as practice has shown, getting an error about overflow is unrealistic. After the type is full, the program does not throw an exception or an error so that it can be processed.
How do you advise to do? Comparison option: if the value is greater then the error message does not fit.
- As I know this can be done with asm together. as done here firststeps.ru/mfc/steps/r.php?393 as the Assembler creates a flag on overflow - Saidolim
- fourIt may be better to use the template <typename T, typename E = _SAFEINT_DEFAULT_ERROR_POLICY> class SafeInt; - Extends the integer primitives to help prevent different types of integers. - cpp_user
2 answers
Overflow of the int
type leads to undefined behavior (UB), and therefore cannot be in the C ++ program.
In practice, the C ++ compiler can remove code that checks int
overflow, since overflow cannot occur.
If int
overflow occurs, then the program’s further behavior is undefined, and any post factum checks are meaningless, since The program is already in an invalid state.
Therefore, the possibility of overflow can be checked only before performing an operation that can cause it, for example:
int x; if (x != INT_MAX) { ++x; } else { // будет переполнение }
Note:
On the x86 platform, there is an instruction into
, but it is not available from C ++.
The gcc compiler has the option -fstrict-overflow
, which allows you to disable optimizations related to the impossibility of overflowing sign types. This allows you to compile old code that violates the prohibition on overflowing int
. However, in the new code it is better not to use this option, and write code that meets the requirements of the standard.
- 2@VladD
int
always signed. (different default signs are only forchar
, but not forshort
,int
and other types) - Abyx - oneHm Could not resist and climbed to the standard. Found 3.9.1 / 2. Live and learn. - VladD
- one@Abyx Where did you read that int overflow leads to UB? - Vlad from Moscow
- one@VladfromMoscow everywhere - Abyx
- 2The only thing I want to say to this is the "f furnace" such standards and compilers. - avp
For gcc there are such built-in functions for checking overflow
- oneAlthough the link can find the answer to the question, it is better to point out the most important thing here, and give the link as a source. If the page to which the link leads will be changed, the response link may become invalid. - From the queue of checks - Saidolim
- @Saidolim, did you mean a request to google:
gcc overflow functions
? - avp