If not, the following gives clever examples of solving this problem:
http://stackoverflow.com/questions/121240/saturating-addition-in-c
I believe the following alternative is the best choice if we want
*portable* and *efficient* code:
unsigned saturate_add_uint(unsigned x, unsigned y)
{
if (y>UINT_MAX-x) return UINT_MAX; else return x+y;
}
Any comments on that?
Thanks in advance,
Nordlöw
I don't know.
> If not, the following gives clever examples of solving this problem:
> http://stackoverflow.com/questions/121240/saturating-addition-in-c
>
> I believe the following alternative is the best choice if we want
> *portable* and *efficient* code:
>
> unsigned saturate_add_uint(unsigned x, unsigned y)
> {
> if (y>UINT_MAX-x) return UINT_MAX; else return x+y;
> }
>
> Any comments on that?
That is AFAICT portable and correct. The link you gave mentions other ways
to achieve the same, in particular using assembler (which is not portable),
using a bigger integer type (which might be unavailable) and detecting
overflow after adding.
As far as detecting overflow afterwards is concerned, this is only portable
for unsigned (!) arithmetic, overflowing signed integers is
always "undefined behaviour" and GCC is known to exploit this knowledge
(i.e. that any signed integer expression doesn't overflow) for
optimisations.
Actually getting saturating operations on signed values is much more
complicated, in particular because INT_MAX-x will break when x is negative
and because -x will break when x is INT_MIN and using twos complement.
Uli