Unary plus

Michael Henning michi at ptcburp.ptcbu.oz.au
Tue Mar 26 15:42:07 AEST 1991


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 ?

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 ?

Similar problems occur if union fields of different sizes and/or types
are to be assigned to each other. For example, given

	union {
		int	i;
		double	d;
	} u;

the behaviour of the assignment

	u.i = (int) u.d;

is undefined, because the storage area for i and d overlap, and i and d have
different types. If I instead write

	tmp = (int) u.d;
	u.i = tmp;

is it necessary to declare tmp as volatile to tell the optimizer not to
get rid of it ?

					Any help greatly appreciated,

						Michi.
-- 
      -m------- Michael Henning			+61 75 950255
    ---mmm----- Pyramid Technology		+61 75 522475 FAX
  -----mmmmm--- Research Park, Bond University	michi at ptcburp.ptcbu.oz.au
-------mmmmmmm- Gold Coast, Q 4229, AUSTRALIA	uunet!munnari!ptcburp.oz!michi



More information about the Comp.std.c mailing list