Contents|Index|Previous|Next

Unintended Grouping of Arithmetic

You may have noticed that in most of the macro definition examples, each occurrence of a macro argument name had parentheses around it. In addition, another pair of parentheses usually surround the entire macro definition. The following is why it is best to write macros that way.

Suppose you define a macro as follows.

    #define ceil_div(x, y) (x + y - 1) / y

This produces macro output whose purpose is to divide, rounding up. (One use for this operation is to compute how many int objects are needed to hold a certain number of char objects.) Then suppose it is used as follows.

    a = ceil_div (b & c, sizeof (int));

This expands into output like the following.

    a = (b & c + sizeof (int) - 1) / sizeof (int);

This output does not do what is intended. The operator-precedence rules of C make it equivalent to an operation like the following.

    a = (b & (c + sizeof (int) - 1)) / sizeof (int);

But what we want is the following result.

    a = ((b & c) + sizeof (int) - 1)) / sizeof (int);

This would mean defining the macro as the following.

    #define ceil_div(x, y) ((x) + (y) - 1) / (y)

This provides the desired result. However, unintended grouping can result in another way. Consider sizeof ceil_div(1, 2). That has the appearance of a C expression that would compute the size of the type of ceil_div (1, 2), but in fact it means something very different. Use the following output as an example of how it expands.

    sizeof ((1) + (2) - 1) / (2)

This would take the size of an integer and divide it by two. The precedence rules have put the division outside the sizeof when it was intended to be inside.

Parentheses around the entire macro definition can prevent such problems. What follows, then, is the recommended way to define ceil_div.

    #define ceil_div(x, y) (((x) + (y) - 1) / (y))