Hacker News new | ask | show | jobs
by throwaway744678 1472 days ago
I don't know which one is faster, but I know that one is not correct (squared approach).
1 comments

Wouldn't the second one also potentially be incorrect due to overflow?
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.