Macro Pitfalls; Misnesting - 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

30
If, within a macro invocation, that macro is redefined, then the new definition takes effect in time for
argument pre-expansion, but the original definition is still used for argument replacement. Here is a
pathological example:
#define f(x) x x
f (1
#undef f
#define f 2
f)
which expands to
1 2 1 2
with the semantics described above.

3.10. Macro Pitfalls

In this section we describe some special rules that apply to macros and macro expansion, and point
out certain cases in which the rules have counter-intuitive consequences that you must watch out for.

3.10.1. Misnesting

When a macro is called with arguments, the arguments are substituted into the macro body and the
result is checked, together with the rest of the input file, for more macro calls. It is possible to piece
together a macro call coming partially from the macro body and partially from the arguments. For
example,
#define twice(x) (2*(x))
#define call_with_1(x) x(1)
call_with_1 (twice)
==> twice(1)
==> (2*(1))
Macro definitions do not have to have balanced parentheses. By writing an unbalanced open paren-
thesis in a macro body, it is possible to create a macro call that begins inside the macro body but ends
outside of it. For example,
#define strange(file) fprintf (file, "%s %d",
...
strange(stderr) p, 35)
==> fprintf (stderr, "%s %d", p, 35)
The ability to piece together a macro call can be useful, but the use of unbalanced open parentheses
in a macro body is just confusing, and should be avoided.
Chapter 3. Macros

Advertisement

Table of Contents
loading

This manual is also suitable for:

Enterprise linux 4

Table of Contents