() ignored in some expressions

Larry Jones scjones at sdrc.UUCP
Thu Apr 12 08:13:17 AEST 1990


In article <1458 at tkou02.enet.dec.com>, diamond at tkou02.enet.dec.com (diamond at tkovoa) writes:
> In article <1272 at sdrc.UUCP> I write:
> 
> >ANSI C requires that all expressions be evaluated as
> >written.  Thus for "a + b + c" the compiler must add a and b
> >first, then add c to the result.
> 
> No.  For "a + b + c", the compiler may add a + c, then add b to the
> result, if it wishes, or if it generates faster code.
> 
> This whole discussion concerns whether () may be ignored.  In ANSI,
> for "(a + b) + c", the () must be obeyed.  Now the compiler must
> add a and b first, then add c, or else do something that has the
> same exact behavior.

That's a common misconception, but it's just not true.  The fact
that most of us refer to this change as "honoring parentheses"
has undoubtedly contributed to the confusion, but that's not what
the standard says.  What the standard says is that all
computations must be carried out according to the given syntax
and semantics -- thus expressions must be evaluated according to
the precedence and associativity of the contained operators.
There's an explicit example of this in section 2.1.2.3 where it
says:

	To illustrate the grouping behavior of expressions, in
	the following fragment

		int a, b;
		/*...*/
		a = a + 32760 + b + 5;

	the expression statement behaves exactly the same as

		a = (((a + 32760) + b) + 5);

	due to the associativity and precedence of these
	operators.  Thus, the result of the sum "(a + 32760)" is
	next added to b, and that result is then added to 5 which
	results in the value assigned to a.

It then goes on to describe how the as-if rule may allow this
expression to be reordered on some machines.
----
Larry Jones                         UUCP: uunet!sdrc!scjones
SDRC                                      scjones at SDRC.UU.NET
2000 Eastman Dr.                    BIX:  ltl
Milford, OH  45150-2789             AT&T: (513) 576-2070
"You know how Einstein got bad grades as a kid?  Well MINE are even WORSE!"
-Calvin



More information about the Comp.lang.c mailing list