Operator Precedence Problems - Red Hat ENTERPRISE LINUX 4 - USING CPP Using Instructions

Using cpp, the c preprocessor
Hide thumbs Also See for ENTERPRISE LINUX 4 - USING CPP:
Table of Contents

Advertisement

Chapter 3. Macros
31

3.10.2. Operator Precedence Problems

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.
Suppose you define a macro as follows,
#define ceil_div(x, y) (x + y - 1) / y
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
objects.) Then suppose it is used as follows:
char
a = ceil_div (b & c, sizeof (int));
==> a = (b & c + sizeof (int) - 1) / sizeof (int);
This does not do what is intended. The operator-precedence rules of C make it equivalent to this:
a = (b & (c + sizeof (int) - 1)) / sizeof (int);
What we want is this:
a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
Defining the macro as
#define ceil_div(x, y) ((x) + (y) - 1) / (y)
provides the desired result.
Unintended grouping can result in another way. Consider
. That has the
sizeof ceil_div(1, 2)
appearance of a C expression that would compute the size of the type of
, but in
ceil_div (1, 2)
fact it means something very different. Here is what it expands to:
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
when it was intended to be inside.
sizeof
Parentheses around the entire macro definition prevent such problems. Here, then, is the recommended
way to define
:
ceil_div
#define ceil_div(x, y) (((x) + (y) - 1) / (y))

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the ENTERPRISE LINUX 4 - USING CPP and is the answer not in the manual?

Questions and answers

Subscribe to Our Youtube Channel

This manual is also suitable for:

Enterprise linux 4

Table of Contents