3 ms·
The basis of this article is incorrect if you care about standards compliance. Signed integer overflow is undefined in C, so checking "a+b<a" is not a correct
by haberman 15y ago
The basis of this article is incorrect if you care about standards compliance. Signed integer overflow is undefined in C, so checking "a+b<a" is not a correct way to test for overflow of signed integers. And this statement, while it may be true in some implementations, cannot be assumed in general:
> Since the addition operation in the CPU is agnostic to whether the integer is signed or unsigned, the same goes for signed integers.
- tedunangst 15y ago? Unless the article was changed, it says "solution 2 does not work, because in the C language, when adding a number to a pointer or to a signed integer, overflow is undefined."
- haberman 15y agoI'm glad that this is corrected later on, but that contradicts the statements made at the beginning of the article: > So, if you want to add two integers a and b (b >= 0), the easiest way to find out if that overflows is to check whether a+b<a (or b; some people think you have to check against min(a,b), but that is unnecessary). This statement is untrue, as is the other statement I quoted.