Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

macros

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?

like image 425
user1582568 Avatar asked Jan 31 '16 12:01

user1582568


People also ask

What are conditional preprocessing macro?

A conditional is a directive that instructs the preprocessor to select whether or not to include a chunk of code in the final token stream passed to the compiler.

Can we pass arguments in macro definition?

Function-like macros can take arguments, just like true functions. To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.

Can we change the value of macro during execution of the program justify?

You can't. Macros are expanded by the Preprocessor, which happens even before the code is compiled. It is a purely textual replacement. If you need to change something at runtime, just replace your macro with a real function call.

What does ## mean in C macro?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.


1 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 don't expand to exactly two arguments.

like image 95
2501 Avatar answered Oct 09 '22 03:10

2501