Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
–
Overflow detection depends on the type of your vars.
If they are unsigned, it is sufficient to detect if the result is lower than one of its operand.
inline unsigned_overflow(unsigned a, unsigned b){
return (a+b)<a;
If both are unsigned, oveflows can only happen if operands are of the same sign and the sign of the result will be different. So there is overflow if the sign of result is different from the sign of its two operands.
inline signed_overflow(int a, int b){
unsigned ua=a, ub=b;
return (int)(((ua^(ua+ub))&((ub^(ua+ub)))<0 ;
–
–
You need to write it on your own. If the arguments are unsigned, it is not too hard to do (just compare if the sum is smaller than one of the addends in the larger input type). The overflow check for signed integer arithmetic can be rather complex, particularly if all three integer types are different. There is a GCC extension that helps somewhat: conversion from unsigned to signed types does not trigger undefined behavior, but reduces the value according to two's complement arithmetic. So you can use this:
unsigned x1 = x1;
unsigned y1 = y1;
bool overflow = (int) (((x + y) ^ x) & (x + y) ^ y))) < 0;
The book Hacker's Delight discusses such topics extensively.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.