8

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?

2
  • 1
    You should read a documentation describing the C++ preprocessor, perhaps the C++11 or C99 standard. It does not work like you are dreaming. Commented Jan 6, 2016 at 16:02
  • I have not idea what you are trying to achieve here... Commented Jan 6, 2016 at 16:02

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Relevant C++ Standard quote: 16.3.4 Rescanning and further replacement
As for "depth" and "width," the preprocessor does both. Moving the open paren from A to B, and given #define I(Q) Q, and using I(A B C), it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.