Michael Veksler wrote on 29/06/2005 00:53:33:
> Robert Dewar wrote on 28/06/2005 22:20:56:
>
> > I am puzzled, why would *ANYONE* who knows C use int
> > rather than unsigned if they want wrap around semantics?
> >
>
> int saturated_mul(int a, int b)
> {
> int ret= a*b;
> if (a == 0 || ret % a == 0)
I of course meant:
if (a == 0 || ret % a == 0 && ret / a == b)
Otherwise, this will not work when a is a power of 2.
> return ret;
> else if ( (a<0) == (b<0) ) // same sign
> return MAX_INT;
> else
> return MIN_INT;
> }
>
> instead of the bizzare:
> int saturated_mul(int a, int b)
> {
> // (unsigned)a*b does not give easy ways to
> // find signed overflow on negatives
>
> if (a==0 || b==0)
> return 0;
>
> bool positive = ( (a<0) == (b<0) );
> if (positive)
> {
> unsigned u_a=a, u_b=b;
> if (a < 0)
> {
> u_a *= -1;
> u_b *= -1;
> }
> unsigned ret= u_a*u_b;
> if (ret % u_a == 0)
I of course meant:
if (ret % u_a == 0 && ret / u_a == u_b)
> return ret;
> else
> return MAX_INT;
> }
> else
> {
> // negative
> even more bizzare code;
> }
>
> It would be really great the standard could
> make my life easier. I need to code to standard,
> not to gcc, so extending gcc may not help....
>
> Michael
>