[Main]
Title=Operator Precedence Problems

[Top]
You may have noticed that in most of the macro definition examples shown
above, each occurrence of a macro argument name had parentheses around
it.  In addition, another pair of parentheses usually surround the
entire macro definition.  Here is why it is best to write macros that
way.
<BR><BR>
Suppose you define a macro as follows,
<PRE>#define ceil_div(x, y) (x + y - 1) / y
</PRE>
whose purpose is to divide, rounding up.  (One use for this operation is
to compute how many <CODE>int</CODE> objects are needed to hold a certain
number of <CODE>char</CODE> objects.)  Then suppose it is used as follows:
<PRE>a = ceil_div (b &amp; c, sizeof (int));
     expands to a = (b &amp; c + sizeof (int) - 1) / sizeof (int);
</PRE>
This does not do what is intended.  The operator-precedence rules of
C make it equivalent to this:
<PRE>a = (b &amp; (c + sizeof (int) - 1)) / sizeof (int);
</PRE>
What we want is this:
<PRE>a = ((b &amp; c) + sizeof (int) - 1)) / sizeof (int);
</PRE>
Defining the macro as
<PRE>#define ceil_div(x, y) ((x) + (y) - 1) / (y)
</PRE>
provides the desired result.
<BR><BR>
Unintended grouping can result in another way.  Consider <CODE>sizeof
ceil_div(1,&nbsp;2)</CODE>.  That has the appearance of a C expression that would
compute the size of the type of <CODE>ceil_div&nbsp;(1,&nbsp;2)</CODE>, but in fact it
means something very different.  Here is what it expands to:
<PRE>sizeof ((1) + (2) - 1) / (2)
</PRE>
This would take the size of an integer and divide it by two.  The
precedence rules have put the division outside the <CODE>sizeof</CODE> when it
was intended to be inside.
<BR><BR>
Parentheses around the entire macro definition prevent such problems.
Here, then, is the recommended way to define <CODE>ceil_div</CODE>:
<PRE>#define ceil_div(x, y) (((x) + (y) - 1) / (y))
</PRE>
