unary +

Mark Brader msb at lsuc.UUCP
Tue Mar 11 16:10:43 AEST 1986


People who don't think (a+b)+c, a+(b+c), and a+b+c should be
interchangeable with respect to optimization -- as they are and
will continue to be -- should consider this toy example:

	#define  C_TO_F(temp)		((temp)*1.8 + 32)
	#define  JUST_ABOVE(temp)	((temp) + epsilon) /* extern epsilon */
	#define  ROUND(real)		((long) .5 + (real))

	scanf ("%d", &melt_pt);
	desired_f_temp = ROUND (JUST_ABOVE (C_TO_F (melt_pt)));

There are, of course, NO unnecessary parentheses in the example*.
After macros are eliminated, the last line ends up as:

	desired_f_temp = ((long) .5 + ((((melt_pt)*1.8 + 32)) + epsilon));

The expression uses 3 macros because that most clearly expresses
what is going on.  (Well, maybe not in this toy case, but there are
lots of real-life examples.)  And the parentheses are there just
because they're needed to make the macros work properly in general*.
They SHOULD NOT have anything to do with the order in which the
3 additions actually occur.

Mark Brader

*For the benefit of any novices to whom this seems strange:  Consider
 the first one, C_TO_F.  If we omitted the inner parentheses, then
 C_TO_F(a+b) would expand to (a + b*1.8 + 32), and only b would be
 multiplied by 1.8.  If we omitted the outer ones, then C_TO_F(c)*k
 would expand to (c)*1.8 + 32*k, and only 32 would be multiplied by k.
 Admittedly temperatures are neither commonly added nor multiplied,
 but it is still very bad practice to omit parentheses from macros
 where they might be needed for such reasons.  End of lecture.



More information about the Comp.lang.c mailing list