There is no direct, portable construct which maps to the overflow condition in C.
Therefore your options are:
- write something in C which does the same thing.
When not using long's it would run a bit more efficient, well, but then it is not so straight forward anymore.
- use HLI (high level inline assembly). I know this is not portable, but if your want to be as efficient as assembly, then this is a case you will have to do this.
First note that in the code you show below, the overflow test does not actually work (I assume your INT16 is signed). The reason is that for (temp1 + temp2), the computation is done on 16 bit and then you convert the already overflowed result to a long. So the result of (temp1 + temp2) is always in the 16 bit range.
So a simple (and slow) version could be:
INT16 temp1, temp2;
INT32 r= (long)temp1 + (long)temp2;
if (r >= 0x8000 || r < -0x8000L) ....
A faster version would do the operation with 16 bits and then detect the overflow somehow else.
For example if the sign of temp1 and temp2 is not the same, it cannot overflow.
If it is the same, the positive positive case is simple with unsigned arithmetic, the negative/negative case has the special -
0x8000+-
0x8000 overflow not to miss too.
What I usually write (not looking at the efficiency, just for simplicity)
INT16 temp1, temp2;
INT32 r= (long)temp1 + (long)temp2;
if (r != (INT16)r) {
...
}
Oh, and BTW, here a snippet for unsigned arithmetic I once wrote.
It's to implement saturation for the addition for unsigned arithmetic. For unsigned the case it a bit simpler as it only can overflow in one direction.
unsigned int AddWithSaturation(unsigned int a, unsigned int b, unsigned int maxN) {
unsigned int res;
if (maxN <= b || maxN - b < a) {
res = maxN;
} else {
res = a + b;
}
return res;
}
Daniel