unary +

Walter Bright bright at dataioDataio.UUCP
Wed Mar 12 04:11:43 AEST 1986


In article <1227 at mtx5a.UUCP> esg at mtx5a.UUCP (ed gokhman) writes:
>An expression a + (b + c) may be calculated by some
>implementations as (a + b) + c. To enforce the
>intended precedence of operations one should use
>a + +(b + c).
>
>Question: what is the rational for not saying that an
>	implementation *must* respect parenthesising
>	as intended rather then providing an extra
>	operator simply to state "i mean these parenthesis" ?

One Answer:
	Compilers frequently parse the expressions into an internal form
which is a binary tree. a+(b+c) would look like:

	  +
	 / \
	a   +
	   / \
	  b   c

Where are the parentheses? They're gone, they are only used in guiding
the parser as it builds the tree. Thus, the optimizer doesn't know where
the parentheses were. Of course, this info could be kludged onto the tree,
but if the unary + operator is used:

	  +
	 / \
	a   U+
	    |
	    +
	   / \
	  b   c

Note that the U+ operator breaks up the n-ary tree of binary + operators,
thus it is easy for the optimizer to not rearrange across U+ operators.
Adding another operator is an easy retrofit to most compilers, far easier
than kludging in parenthesis information.

Languages that do not allow an optimizer to rearrange trees within
certain limits cause slow code to be generated. I take advantage of the
compilers I use by knowing what rearrangements they do, so that I can
write code that is more aesthetically pleasing, knowing that the optimizer
will rearrange it into a faster sequence. For example,

	a+5+6 is turned into the tree (a+5)+6. If the compiler
	couldn't rearrange trees, it couldn't produce the
	'optimized' a+11 tree.



More information about the Comp.lang.c mailing list