Expression sequencing query

Joel Coltoff coltoff at burdvax.UUCP
Fri Oct 10 01:05:47 AEST 1986

In article <160 at geac.UUCP>, len at geac.UUCP (Leonard Vanek) writes:
> The one thing that is clear from all of the discussion on
> the problem of expression sequencing is that one can never
> be sure of the order in which an expression in C will be
> evaluated.

Not always true. Logical expressions are evaluated left to right.

> I still believe that it is a pity that C (even Ansi C) does not even
> let the programmer tell it what order is desired by the use
> of parentheses! To ignore parentheses in determining the
> evaluation order (i.e. (a+b)+c does not guarantee that a and
> b are added first) causes problems with round off errors,
> not just side effects -- and is totally counter-intuitive.

Agreed. But keep this in mind. C can change the order in which it
evaluates expressions, we told you that when you took this job,
what it doesn't do is change the order in which it evalutes statements.
If you really want to do (a+b) + c then do it like this

	x = a + b;
	x += c;

Yes it uses more variables, generates more code and is less efficient but
it gets the correct answer. This is often much more important than
any of the other considerations we make when we write programs.

Now to throw in my few shekels. When you do something like

	a = (b=1,b) + (b=2,b) + (b=3,b);

or more realistically

	if ( a < b || ( c = ( x/y ) ) == 42 || d == data[i] )

you deserve to get burned. Sure the langauge lets you do things like
assign a value to c and compare it to 42 in the same expression but
keep in mind that that assignment isn't done on each pass through that
block of code.

More information about the Comp.lang.c mailing list