user1582568
user1582568

Reputation: 288

Is there a way to force C preprocessor to evaluate macro arguments before the macro

I have a number of macros in the form

#define F(A,B)   Some function of A and B

and for readability I would like to define arguments for these macros e.g.

#define C A,B

so that I can say

F(C)

but the preprocessor tries to expand F before C and complains that F needs 2 arguments. Is there a way to make it expand C before it expands F so that the error does not occur?

Upvotes: 9

Views: 4443

Answers (2)

Dsonophorus
Dsonophorus

Reputation: 11

Macro expansion (erroneously) does not trigger argument recount. Therefore, any time macro expansion of a function invocation results in a different number of arguments, it must be forced to recount the number of arguments.

Use this pattern to force expansion and recount before invocation:

//Step 1: wrap the entire affected argument pack in parenthesis
#define mFn(A, ExpandingArgument) mFn1((A, ExpandingArgument))

//Step 2: intermediary layer without ## or # is required to actually expand
#define mFn1(...) mFn2(__VA_ARGS__)

//Step3: Paste the parenthesized arguments to final function identifier to trigger 
//       function like macro interpretation and invocation
#define mFn2(...) mFn3##__VA_ARGS__

//Step4: Implement the actual function as if the standard were written correctly
#define mFn3(A,B,C,...) //Do things

Upvotes: 0

2501
2501

Reputation: 25752

You can use an intermediate macro that takes a variable number of arguments:

#define F1(A,B) 
#define F(...) F1(__VA_ARGS__)

#define C A,B

int main(void) {
    F(C)
    F(1,2)
    return 0;
}

This should compile. You will still get a compilation failure if you pass more or less than two arguments, or arguments that don't expand to exactly two arguments.

Upvotes: 12

Related Questions