Brent Faust
Brent Faust

Reputation: 9309

C preprocessor tokenization does not expand macro?

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)?

Upvotes: 10

Views: 2203

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

#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.

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122383

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.

Upvotes: 5

Related Questions