4 ms·
That is undefined behavior.
by jcranmer 6y ago
That is undefined behavior.
- arcticbull 6y agoWell son of a bucket, you're right. What about this? T const highOrderBitMask = (1 << ((sizeof(T) * 8) - 1)); T const hobA = (a & highOrderBitMask); T const hobB = (b & highOrderBitMask); T const hobR = ((a + b) & highOrderBitMask); if ((hobA == hobB) && (hobA != hobR)) { /* Overflow */ } Or is it undefined behavior to assume a 2's complement representation also. [edit] Yep, 2's is only required for C++20, not C, and worse, it's permitted for an implementation to trap on overflow. Back to the drawing board.
- jcranmer 6y agoIt is undefined behavior if a signed integer arithmetic overflows. If T is signed, the first and fourth lines are undefined behavior. The representation of signed numbers is implementation-defined, not undefined.
- arcticbull 6y agoOk, 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?