Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Saturated Arithmetic in gcc/g++

887 views
Skip to first unread message

Nordlöw

unread,
Nov 28, 2008, 5:07:19 AM11/28/08
to
Does GCC have any platform independent built-ins for saturated
arithmetic?

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

Ulrich Eckhardt

unread,
Nov 29, 2008, 5:07:25 AM11/29/08
to
Nordlöw wrote:
> Does GCC have any platform independent built-ins for saturated
> arithmetic?

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

0 new messages