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