C (92/207)

From:Volker Barthelmann
Date:13 Dec 99 at 02:07:00
Subject:Re: Re: Overflow

From: Volker Barthelmann <volker@vb.franken.de>

On Sun, 12 Dec 1999, Steven Dobbs wrote:

> 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?

The expression will be computed as int.

> >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.

*shudder*! Of course not. The type a subexpression is computed with
depends on the type of its operands, not left or right.

First, short types ([unsigned] char/short) are promoted to signed int (if
the entire value range of the type fits into a signed int) or unsigned int
(otherwise). On the Amiga always signed int will be chosen.

After both operands have been promoted, the type with the bigger value
range is chosen to compute the expression. If none of the types is a
subset of the other one, the unsigned attribute will be preserved.

This is done for each subexpression according to associativity, e.g. in

short s;int i;long l;
s*i*l

s will be promoted to int and s*i computed as int. Then the result will be
promoted to long and multiplied with l.

In l*i*s all subexpressions would be computed as longs but that is due to
associativity (l*i is computed first).

> 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.

No. Unless parentheses are used the associativity is left-to-right for the
typical arithmetic operators. Therefore (T2-T3) will first be multiplied
by 11 and then divided by 4. A compiler must not rearrange this unless it
can ensure that the result will be the same (which is clearly not the case
here).

Volker