Am 17.08.23 um 23:27 schrieb Alan Cox:
How do you check over/underflow in C without wasting memory?

If your compiler is smart enough then for unsigned maths

         r = a + b;
        if (r < a)

will be optimized nicely. I've not checked if sdcc knows that and will
turn it into a carry check at least for uint8 and uint16.

For signed maths there is not nice portable approach because signed maths
overflow is undefined in C and indeed there are even processors where you
get a maths exception for your trouble.

Fortunately, there is now (as mentioned by Benedikt a few minutes before you): ISO C23 introduced checked integer arithmetic (see section 7.20 of the ISO C23 standard). SDCC partially (long long support is still missing, the rest should work) supports it as of SDCC 4.3.0. However, in SDCC 4.3.0, it is not very efficient. Since the merge of the genconstprop branch recently, SDCC generates much better code, though. And once more users use the new feature, we are likely introduce more optimizations for it.

Philipp

P.S.: Checking for signed overflow is a bit more complicated in assembler, too: Not all processors have an overflow flag (i.e. xor of carry-in and carry-out of topmost bit) or an easy way to check it.



_______________________________________________
Sdcc-user mailing list
Sdcc-user@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/sdcc-user

Reply via email to