Unary plus

Keizer E G keie at cs.vu.nl
Wed Mar 27 02:36:52 AEST 1991


michi at ptcburp.ptcbu.oz.au (Michael Henning) writes:

>In my copy of Harbison & Steele (1987) is a section about the unary plus
>operator in ANSI-C.
>It basically states that the unary plus operator may be used to force
>a particular order of evaluation. H & S quote an example:

>If x and y are floating point variables, the expressions

>	((x+y)-x)-y
>and
>	(x+y)-(x+y)

>do not necessarily give the same result (or zero, for that matter) because
>the order of evaluation is undefined. The go on to say that to force
>evaluation order as indicated by the brackets in the first expression,
>one may write

>	+((+(x+y))-x)-y

>In my copy of the ANSI-C standard (X3J11/90-013, Feb 14th, 1990), I could
>not find any mention of this behaviour, so I assume that it was dropped from
>the standard after H & S published the book. Is this correct ?

Yes. The `special' effect that a unary plus enforced evaluation order has
disappeared. You have to make a difference between evaluation order
and the re-ordering of the expression. The current Standard allows
any evaluation order but restricts re-ordering with the as-if rule.
To illustrate the point:
	( x1 + y1 ) * ( x2 + y2 )
The Standard does not state in which order the additions "x1+y1" and
"x2+y2" have to be done. The only way in which this could affect
the result is when one of x1, x2, y1 and y2 produce side effects.
The best way to see this is by viewing the expression as a tree.
The compiler is allowed to compute the leaves and perform the operations
in any order as long as the expression tree itself is not changed.
That is you have to evaluate x1 and y1 before adding them, x2 and y2
before adding them and perform the multiplication only after the result
from additions is known.
To confuse the matter a bit I have to state that the compiler can
actually use any which way to calculate the expression, as long as the result
(including possible overflow) is a result that is possible under the
rules stated above. The reason for this is that nobody could tell
the difference (as long as they are not reading the code produced).
For floating point expressions all this means that the programmer can
assume the a conforming compiler will not fiddle with his expressions.

>Which brings me to my next question...

>If I want to enforce evaluation order by assigning to temporary variables, e.g.

>	tmp = x + y;
>	tmp -= x;
>	tmp -= y;
>	result = tmp;

>is it necessary to declare tmp as volatile to prevent the optimizer from
>optimizing tmp out of existence ?  Or are there some rules that say that the
>optimizer should not get rid of tmp in this case ?

No, it is not necessary to declare tmp as volatile. In fact as stated
above this way of calculating the result only makes sense if x or y
produce side-effects.

I refrain from giving an answer to your third question.

Ed Keizer



More information about the Comp.std.c mailing list