Hacker News new | ask | show | jobs
by saghm 1472 days ago
Wouldn't the second one also potentially be incorrect due to overflow?
1 comments

Yes. 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.