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