cesss
cesss

Reputation: 893

Can the parameter names in a C macro have side effects from previous definitions?

I know about the argument prescan when an argument is used in a C macro, but that happens when you use an already defined macro. However, when you define it, do you need to have any special care at choosing the parameter names? Does the preprocessor parse the macro in an "atomic" way so that parameter names are not expanded?

I mean, imagine this scenario:

#define MYVAL {is this safe?}
#define ADDVALUES(MYVAL,YOURVAL) do{(MYVAL)+(YOURVAL);}while(0)

int val=ADDVALUES(1,3);

How is the ADDVALUES macro parsed? Is MYVAL expanded before defining the ADDVALUES macro?

I have not read any warning about choosing the parameter names in a macro, so I tend to believe their name is not expanded before the macro is parsed (I have read warnings about naming local variables in macros, about the macros names themselves, about swallowing the semicolon, etc., but nothing about choosing the parameter names).

Upvotes: 3

Views: 342

Answers (2)

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10123

The scope of the parameter MYVAL is distinct from that of the object-like macro MAYVAL. Quoting from the relevant part of the Standard, 6.10.3,p10:

The parameters are specified by the optional list of identifiers, whose scope extends from their declaration in the identifier list until the new-line character that terminates the #define preprocessing directive.

The last line in the example given will be expanded as

int val=do{(1)+(3);}while(0);

Upvotes: 3

stark
stark

Reputation: 13189

I tried with gcc 4.8.5

#define NV1 a
#define V1(NV1) b NV1
V1(foo)

gcc -E test.h

Result

b foo

So parameter name is not expanded as a macro and overrides the earlier conflicting definition

Upvotes: 2

Related Questions