Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using preprocessor macros to compose another macro call

Suppose I have a C++ preprocessor macro defined as follows:

#define X(s) std::cout << #s

if I use it directly:

int main() {
    X( hello );
}

It works as expected and "hello" is printed on the console.

If I define another macro that calls it:

#define Y X( hello )
#define X(s) std::cout << #s

int main() {
    Y;
}

It still works.

However if I try to compose the call to X from two or more different macros, I get a whole bunch of errors:

#define A X(
#define B hello
#define C )

#define X(s) std::cout << #s << '\n'


int main()
{
    A B C;
}

See output at: http://cpp.sh/5ws5k

Why can't I compose a macro call from two or more macro expansions, doesn't preprocessor expand them recursively?

like image 343
Levi Haskell Avatar asked Jan 06 '16 15:01

Levi Haskell


People also ask

Can a macro call another macro in C?

Here is an example of how to run another macro from a macro using the Call Statement. Just type the word Call then space, then type the name of the macro to be called (run). The example below shows how to call Macro2 from Macro1. It's important to note that the two macros DO NOT run at the same time.

What is the difference between macro and preprocessor?

Preporcessor: the program that does the preprocessing (file inclusion, macro expansion, conditional compilation). Macro: a word defined by the #define preprocessor directive that evaluates to some other expression. Preprocessor directive: a special #-keyword, recognized by the preprocessor. Save this answer.

What is nested macro in C?

A nested macro instruction definition is a macro instruction definition you can specify as a set of model statements in the body of an enclosing macro definition. This lets you create a macro definition by expanding the outer macro that contains the nested definition.

What is macro processing in preprocessor?

Macros allow you to write commonly used PL/I code in a way that hides implementation details and the data that is manipulated and exposes only the operations. In contrast with a generalized subroutine, macros allow generation of only the code that is needed for each individual use.


1 Answers

Why can't I compose a macro call from two or more macro expansions, doesn't preprocessor expand them recursively?

You can compose macros. The pre-processor does expand macros recursively.

However, it doesn't expand the macros width first. It expands them depth first.

You are running into a problem because you want the pre-processor to expand the macros width first.

You can read more about recursive macro expansion in 16.3.4 Rescanning and further replacement of the C++11 standard.

like image 128
R Sahu Avatar answered Nov 10 '22 00:11

R Sahu