On Thu, 16 Oct 2003, Andreas Kahari wrote:

>

> In article <bmljkn$86h$(E-Mail Removed)>, Grumble wrote:

> > gc wrote:

> >>

> >> If I have double variables, d,u,v,w,x. Soes the standard ensure that

> >> while assigning a value to d as,

> >> d=(u+v)-(w+x);

> >> u+v will be added first then w+x and then they will be added together

> >> and that the compiler will not evaluate the above expression in

> >> anyother order.

> >>

> >> Just wondering, since addition of doubles is not associative.
The order of operations is not specified, except that (w+x) will be

subtracted from (u+v); the compiler can't decide to subtract w from

(u+v), and then subtract x from the result, *UNLESS* the answer would

be exactly the same (the "as if" rule) -- in which case who cares how

it was computed?

> > The subtraction will be carried out last, but AFAIK the additions

> > could be done in either order. If you want to force a specific

> > evaluation order, you could use an extra variable.

>

> double t1, t2;

>

> t1 = u + v;

> t2 = w + x;

>

> d = t1 - t2;

>

> AFAIK, there's nothing stopping the compiler from generating

> code that calculates t2 before t1.
Practically, that's true. However, the code *must* behave *AS IF*

t1 was calculated before t2, because the semicolons introduce

sequence points.

> I'm not sure the finer details of floating point arithmetics is

> an issue here at all.
On some systems (which may or may not be conforming, I don't know;

I don't follow floating-point stuff

, we can have

double d = 3.14;

double e = 4.72;

double f = d/e;

printf("%g %g\n", f, d/e);

and get two different numbers, because the FPU registers use

slightly wider representations than the actual type 'double'

objects. That's why order-of-operations matters in general,

in practice.

And specifically about associativity, you know that

double d = 1e10, e = 5, f = 5;

double r1, r2;

r1 = (d+e)+f;

r2 = d+(e+f);

can produce (r1 != r2) (for suitable values of 5, of course).

It's plausible that something like that could be at stake

in the OP's code; I don't feel like running through all possible

values of (u,v,w,x) right now.

HTH,

-Arthur