4 ms·
Personally, I choose to just write non-standard C and turn on my compiler's option to define signed overflow as wrapping. Note that without that option, multip
by Asooka 4y ago
Personally, I choose to just write non-standard C and turn on my compiler's option to define signed overflow as wrapping.
Note that without that option, multiplication of unsigned shorts is undefined on platforms where sizeof(unsigned short) = sizeof(int)/2. That is due to the integer promotion rules. Let's say shorts are 16-bit and ints are 32-bit, which is the case on all consumer devices. Integer promotion rules lead to both unsigned short operands being first converted to ints before multiplication. If they are both equal to 0xffff, then the result is bigger than INT_MAX, and thus undefined. Which means that just multiplying two unsigned shorts is dangerous unless you cast them to unsigned ints first. Here is a godbolt link demonstrating the problem: https://gcc.godbolt.org/z/3445PEGqY https://gcc.godbolt.org/z/3445PEGqY
I have never seen the benefit of leaving signed overflow undefined, so I just make it defined to avoid weird problems like that. Most people think that all unsigned arithmetic is well defined, but unfortunately that's false.
- kevin_thibedeau 4y ago> I have never seen the benefit of leaving signed overflow undefined The benefit is that architectures are free to implement it with saturating arithmetic.
- Asooka 4y agoThat's fine. Define it as saturating on those architectures. Just being defined as "this never happens" is hugely detrimental to predicting how you're program behaves.
- Quekid5 4y ago> I have never seen the benefit of leaving signed overflow undefined, IIRC it affords huge optimization opportunities, esp. around loops. (Now, whether you like that or not is a value judgment, but a lot of people do want those optimizations.)