4 ms·
Wouldn't the second one also potentially be incorrect due to overflow?
by saghm 4y ago
Wouldn't the second one also potentially be incorrect due to overflow?
- pjscott 4y agoYes. Suppose that both numbers are positive, that x>num, and that x+num is bigger than INT_MAX. In that case we hit signed integer overflow, which is undefined behavior. If signed integer overflow happens to wrap around, which it might, then the result could be negative and the function would return the wrong result. Or anything else could happen; undefined behavior is undefined. In practice, just writing "abs(num) > x" gives quite good machine code, and it does so without introducing hard-to-see bugs.
- deleted 4y ago[deleted]