Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

macros

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

like image 653
cesss Avatar asked Dec 05 '25 04:12

cesss


2 Answers

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);
like image 171
M. Nejat Aydin Avatar answered Dec 07 '25 19:12

M. Nejat Aydin


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

like image 45
stark Avatar answered Dec 07 '25 19:12

stark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!