Evaluation of if's

Chris Torek torek at elf.ee.lbl.gov
Tue Jun 18 16:27:57 AEST 1991


Others have cleared up the rest of this already, but one point remains.
To avoid confusion, I will also restate some of the previous corrections.

In article <1991Jun13.184843.508 at ulkyvx.bitnet> pgheit01 at ulkyvx.bitnet writes:
>The statement if ((i = 1) == (i = 2)) is valid.

Syntactically, yes; semantically, no.

>ANSI C evaluates conditions from left to right.

False; evaluation proceeds from sequence point to sequence point in an
otherwise undefined manner (with some exceptions; see the standard for
exact details).  The short-circuit boolean-result operators && and ||
introduce sequence points, so the left hand side of any such operator
is evaluated before the right hand side, and evaluation stops as soon as
the result is known; but little else can be said.  Certainly `left to
right' is far too strong a statement.

>My C teacher just loved to slip in questions like this one to see if anyone
>knew the finer details of the precedence table. :-)

Evaluation order and precedence are orthogonal concepts.  For instance,
consider the order and precedence relations in:

	i = *p++;

Precedence affects the parsing of `*p++' so that it is interpreted as
*(p++) and not (*p)++, and (i = (*(p++))) and not (i = *p)++.  The most
likely evaluation order on many machines, however, is this:

	tmp = *p;
	i = tmp;
	p++;

rather than the `direct' but inefficient sequence:

	tmp = p;
	p++;
	tmp = *tmp;
	i = tmp;

You would do future students a great service to go to your C teacher
and tell him, her, or it% to obtain and read a copy of X3.159-1989, the
ANSI C standard.  [%Perhaps the C teacher is a CAI program.  `He' alone
may be sexist, but `s/he' and variants are animist.  Personally, I
think we should just give in and use `it' as the generic third-person
singular.$]  [$If you needed a half-smiley here, you are not reading
these footnotes with the proper dry tone.  (How do you tell a CAI
program to read the standard, anyway?)]  Teachers who concentrate on
syntax over semantics are probably missing the point.
-- 
In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 415 486 5427)
Berkeley, CA		Domain:	torek at ee.lbl.gov



More information about the Comp.lang.c mailing list