Macro Arguments - 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

Chapter 3. Macros
3.2. Function-like Macros
You can also define macros whose use looks like a function call. These are called function-like macros.
To define a function-like macro, you use the same
immediately after the macro name. For example,
#define lang_init()
lang_init()
==> c_init()
A function-like macro is only expanded if its name appears with a pair of parentheses after it. If you
write just the name, it is left alone. This can be useful when you have a function and a macro of the
same name, and you wish to use the function sometimes.
extern void foo(void);
#define foo() /* optimized inline version */
...
foo();
funcptr = foo;
Here the call to
foo()
function. If the macro were to be expanded, it would cause a syntax error.
If you put spaces between the macro name and the parentheses in the macro definition, that does not
define a function-like macro, it defines an object-like macro whose expansion happens to begin with
a pair of parentheses.
#define lang_init ()
lang_init()
==> () c_init()()
The first two pairs of parentheses in this expansion come from the macro. The third is the pair that was
originally after the macro invocation. Since
those parentheses.

3.3. Macro Arguments

Function-like macros can take arguments, just like true functions. To define a macro that uses argu-
ments, you insert parameters between the pair of parentheses in the macro definition that make the
macro function-like. The parameters must be valid C identifiers, separated by commas and optionally
whitespace.
To invoke a macro that takes arguments, you write the name of the macro followed by a list of actual
arguments in parentheses, separated by commas. The invocation of the macro need not be restricted to
a single logical line--it can cross as many lines in the source file as you wish. The number of arguments
you give must match the number of parameters in the macro definition. When the macro is expanded,
each use of a parameter in its body is replaced by the tokens of the corresponding argument. (You
need not use all of the parameters in the macro body.)
As an example, here is a macro that computes the minimum of two numeric values, as it is defined in
many C programs, and some uses.
c_init()
will use the macro, but the function pointer will get the address of the real
c_init()
lang_init
directive, but you put a pair of parentheses
#define
is an object-like macro, it does not consume
15

Advertisement

Table of Contents
loading

This manual is also suitable for:

Enterprise linux 3

Table of Contents