简体   繁体   中英

How to define a C macro expression?

how does one define a macro expression in C, whose arguments are also expressions?

The problem I am tackling is how to write an expression MAX(X,Y) that takes in the expressions X and Y (such as x++ or x+2 ) and returns the maximum of the two. This expression should be defined in as a preprocessor macro.

Answer from a related post:

#define MAX(a, b) ((a) > (b) ? (a) : (b))

and I am aware of the risks involved with x++ in a macro (can be evaluated twice).

Kind regards

This is possible with GCC by using a specific expression construct, see: Statements and Declarations in Expressions .

Here is an example:

#define INTMAX(A, B) ({ int _a = (A), _b = (B) ; _a > _b ? _a : _b ; })

You can use typeof instead of int if you don't know the type of arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM