Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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



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 :)


IMHO, 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.


You might like this blog post, We Need Hardware Traps for Integer Overflow.

https://blog.regehr.org/archives/1154


I 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?


Ohhh, I think it also needs to check if (b > 0) in the first arm and (b < 0) in the second arm. -_-


You 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/


INT_MIN + b right?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: