3 ms·
Regarding undefined behavior, one thing I very often assume is 2's complement math with wraparound on overflow. That assumption has never failed for me, so it r
by phkahler 9y ago
Regarding undefined behavior, one thing I very often assume is 2's complement math with wraparound on overflow. That assumption has never failed for me, so it really bothers me that this is undefined in the standard.
I have used processors that have saturating arithmetic and I even used that feature, but even there compiler defaulted to the more common rollover behavior.
- usefulcat 9y agoAssuming you're using gcc or something with similar options, you should have a look at -fwrapv if you haven't already.
- Animats 9y agoFor C, the standard specifies that unsigned arithmetic wraps around, while integer arithmetic overflow is undefined. I once suggested, back when there were machines that weren't byte-oriented or twos complement, that wraparound arithmetic should be requested with unsigned int x; x = (x + 1) % 0xffff; or something similar. That way, you get the same result on all platforms, regardless of word length. If the hardware can truncate cheaply, the compiler can optimize "%" such expressions easily. Other than that, overflow should be an error.