Reputation: 853
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?
Upvotes: 7
Views: 3495
Reputation: 206717
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.
Upvotes: 8