Self-Referential Macros - Red Hat ENTERPRISE LINUX 3 - USING CPP Using Instructions

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

Advertisement

30
#define min(X, Y)
({ typeof (X) x_ = (X);
typeof (Y) y_ = (Y);
!
(x_
y_) ? x_ : y_; })
The
notation produces a compound statement that acts as an expression. Its value is the
({ ... })
value of its last statement. This permits us to define local variables and assign each argument to one.
The local variables have underscores after their names to reduce the risk of conflict with an identifier
of wider scope (it is impossible to avoid this entirely). Now each argument is evaluated exactly once.
If you do not wish to use GNU C extensions, the only solution is to be careful when using the macro
. For example, you can calculate the value of
min
in
:
min
#define min(X, Y)
...
{
int tem = foo (z);
next = min (x + y, tem);
}
(where we assume that

3.9.5. Self-Referential Macros

A self-referential macro is one whose name appears in its definition. Recall that all macro definitions
are rescanned for more macros to replace. If the self-reference were considered a use of the macro,
it would produce an infinitely large expansion. To prevent this, the self-reference is not considered a
macro call. It is passed into the preprocessor output unchanged. Let's consider an example:
#define foo (4 + foo)
where
is also a variable in your program.
foo
Following the ordinary rules, each reference to
rescanned and will expand into
The self-reference rule cuts this process short after one step, at
definition has the possibly useful effect of causing the program to add 4 to the value of
is referred to.
foo
In most cases, it is a bad idea to take advantage of this feature. A person reading the program who
sees that
is a variable will not expect that it is a macro as well. The reader will come across the
foo
identifier
in the program and think its value should be that of the variable
foo
the value is four greater.
One common, useful use of self-reference is to create a macro which expands to itself. If you write
#define EPERM EPERM
!
((X)
(Y) ? (X) : (Y))
returns type
foo
int
(4 + (4 + foo))
\
\
\
, save it in a variable, and use that variable
foo (z)
).
will expand into
foo
; and so on until the computer runs out of memory.
Chapter 3. Macros
; then this will be
(4 + foo)
. Therefore, this macro
(4 + foo)
, whereas in fact
foo
wherever
foo

Advertisement

Table of Contents
loading

This manual is also suitable for:

Enterprise linux 3

Table of Contents