3
votes

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

2
Ugh - might have to go scan the source of Clang to get an answer for this unless we have a local language lawyer handy.Michael Dorgan
If I take your code, minus the do while(0) part, and drop it into a compiler, I get no errors - the top macro isn't expanded or used. Seems that is at least part of the answer you want. onlinegdb.com/H1ws9g7GPMichael Dorgan

2 Answers

3
votes

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);
2
votes

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