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

What you should be doing for checked arithmetic with GCC is use the builtins for those that aren’t aware;

https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins...



It would be nice to see something like that standardised so you could use it in portable code.

It doesn't solve the problem though. You still need to write some code for what to do if there's an overflow, and you need separate handling for underflow. So the signed case is now:

  extern void g1(int); 
  extern void g2(int); 
  extern void g3(int); 
  void f(int x, int y)
  {
      int x_minus_y;
      if(__builtin_ssubl_overflow(x, y, &x_minus_y))
         g1(x_minus_y);
      else if(x > y)
         g2(...); /* overflow */
      else
         g3(...); /* underflow */
  }
Work in progress. I've given up on figuring out what arguments to pass to g2 and g3. Since the difference won't fit in an int, you would need to offset-adjust the value somehow in order to fit it in an int. Seems messy. Maybe you can think of something simpler.




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

Search: