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

I have several 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, for example

#define C A,B

so i can say

F(C)

but the preprocessor tries to extend F to C and complains that F needs 2 arguments. Is there a way to get him to expand C before he extends F so that the error does not occur?

+4
source share
2 answers

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 do not expand to two arguments.

+6

() . , , .

:

//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
0

Source: https://habr.com/ru/post/1626743/


All Articles