3 ms·
Ok, I think I've got it this time -- and incidentally, a new interview question. if (((a > 0) && (a > INT_MAX - b)) || ((a < 0) && (a < INT_MIN - b)))
by arcticbull 6y ago
Ok, I think I've got it this time -- and incidentally, a new interview question.
if (((a > 0) && (a > INT_MAX - b)) ||
((a < 0) && (a < INT_MIN - b))) { /* Would Overflow */ }
Not standard, but not undefined either are the checked intrinsics:
__builtin_add_overflow(a, b, &x) == false
Thanks, that was a fun exercise :)
- jcranmer 6y agoIMHO, C really should just standardize the standard checked overflow intrinsics. It's a lot saner than having users try to guess the correct overflow matching pattern (it's worse for multiplication), and many architectures make detecting overflow pretty trivial.
- MaxBarraclough 6y agoYou might like this blog post, We Need Hardware Traps for Integer Overflow. https://blog.regehr.org/archives/1154 https://blog.regehr.org/archives/1154
- deleted 6y ago[deleted]
- MaxBarraclough 6y agoI think I might be missing the intent of this exercise, but that expression risks overflow (and undefined behaviour) when b is not equal to zero, right?
- arcticbull 6y agoOhhh, I think it also needs to check if (b > 0) in the first arm and (b < 0) in the second arm. -_-
- MaxBarraclough 6y agoYou might be interested in a related challenge: write a function in standard C++ that returns the difference between any pair of int32_t values. This cropped up on StackOverflow. It's tricky enough to trip up the incautious. https://stackoverflow.com/a/61711253/ https://stackoverflow.com/a/61711253/
- mlyle 6y agoINT_MIN + b right?