10

1) Why is the macro MSG not expanded in the following expression?

#define MSG Hello #define HELLO(name) MSG ## name void HELLO(Dave) () {} 

Using

gcc -E -P test.cpp 

Output:

void MSGDave () {} 

MSG name expands to Hello Dave. And MSG # name expands to Hello "Dave". So what causes gcc not to expand MSG ## name?

2) Is there a workaround?

Is there a preprocessor directive like defined(x), such as expand(x)?

2 Answers 2

5

Because macro arguments are not substituted when preceded or followed by a ## operator.

C11 §6.10.3.1 Argument substitution

After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.

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

1 Comment

Nice. You nailed half the question -- why it isn't expanded. Then @n.m. gave the other very important half -- the workaround.
3
#define MSG Hello #define cat(x, y) x ## y #define cat2(x, y) cat(x, y) #define HELLO(name) cat2(MSG,name) 

Live demo @ ideone.

1 Comment

Excellent! This is the 2nd and most important half of the answer - the workaround. @Yu responded first with the reason -- this 'bug' is by design.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.