From: | James S. Adelman |
Date: | 12 Dec 99 at 22:41:02 |
Subject: | Re: Re: Overflow |
From: "James S. Adelman" <j.adelman@ukonline.co.uk>
Steven Dobbs wrote on Sun, 12 Dec 1999 17:35:14 +0100 in �PRIV.amiga-c:
> From: Steven Dobbs <steven.dobbs@cableinet.co.uk>
>
> Hello Lee
>
>
> > if( ( T1 + ( (T2-T3)*11/4 ) ) > 205)
> > {
> > do whatever
> > }
>
> > Am I right in thinking that the fact that T1,T2 and T3 are unsigned chars
> > doesnt matter if say T3 is bigger than T2. What size of storage will the
> > compiler use to calculate the expression to compare to 205? Will there be
> > any problems with the expression over/under flowing?
>
> From a course I did in c, I was told by the lecturer that in those sorts of
> circumstances, c will take the type on the left and apply that. so I
> _think_ its like this:
>
> float f; unsigned char c;
>
> (f*c) returns a float, but (c*f) will return an unsighned char. To force the
> latter to return a float, you do this, (float)c*f
>
> in the same way, f*c can be made to return an unsigned char with (unsighned
> char)f*c
>
> in your equation
>
> T1 + ( (T2-T3)*11/4 ) ) > 205)
>
> 11 and 4 are considered integers so will probably return for 11/4 the value
> 2. if you want fractional values for 11/4, perhaps this will work 11.0/4.0
> or definately
>
No, it should multiply by 11, and then divide by 4, then add T1, then
compare the char representation of 205. If the values that T1, T2 and
T3 take are restricted, it may be the case that the error introduced
can be ignored (if the values 205-206 are not possible for the
whole expression, just use 11L to avoid overflow) or resolved using
byte arithmetic.
> T1 + ( (T2-T3)*(float)11/4 ) ) > 205)
>
Better anyway to use 2.75 in place of (float)11/4, but even better is
if (
(
(4*T1)
+(11*(T2-T3))
-820
)
>0
)
{...
(multiplied both sides by 4, and subtracted the resultant 820.)
Far more efficient, since you are using only integers, and 820 is per se long.
But the 2.75 version is probably more readable.
> I hope thats correct and that it helps.
>
> Regards
> --
> Steven Dobbs
>
> > -> Spread the URL: http://www.onelist.com/subscribe/amiga-c <-
>