Implementing / enforcing wraparound arithmetic in C [closed]

雨燕双飞 提交于 2019-12-13 09:48:55

问题


The C standard says that overflow in arithmetic is undefined.

I would like to know how to implement wraparound arithmetic in a performance-friendly way. This means that overflow checking solutions like presented here are not an option (as they slow the operation by about an order of magnitude).

I assume the solution would involve writing an assembly routine to do this. Is there a library available that does this (preferably for multiple architecture, although x86 is a must)?

Alternatively, is there a compiler flag (for gcc & clang) that makes the compiler enforce wraparound semantics for integer arithmetic?


回答1:


Signed overflow is undefined. Unsigned overflow wraps. Implementing signed wraparound arithmetic is mostly a matter of doing everything in unsigned math. There are a few things to be careful about, though:

  1. unsigned short and unsigned char arithmetic works by converting the operands to either int or unsigned int first. Usually int, unless you're on a weird setup where int doesn't have enough range to store all unsigned short values. That means that converting short or char to unsigned short or unsigned char for arithmetic can still produce signed integer overflow and UB. You need to do your math in unsigned int or larger to avoid this.
  2. unsigned->signed conversion is technically implementation-defined when the original value is beyond the range of the result type. This shouldn't be a problem on most compilers and architectures.

Alternatively, if you want to go the compiler flag route, -fwrapv makes signed overflow wrap for addition, subtraction, and multiplication on GCC and Clang. It doesn't do anything about INT_MIN / -1, though.



来源:https://stackoverflow.com/questions/40731543/implementing-enforcing-wraparound-arithmetic-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!