在C中为MIN定义2个数字

Min*_*ina -4 c macros c-preprocessor

#define MIN (A,B) ((A)<(B)?(A):(B)) 要么 #define MIN (A,B) ((A < B)? A : B )

请选择一个答案,为什么?

xan*_*tos 6

我们有这个表达式:

int c = MIN(x == y, 1);
Run Code Online (Sandbox Code Playgroud)

我们来试试吧 #define MIN (A,B) ((A < B) ? A : B )

在C中,==运算符的优先级较低<(因此x == y < z相当于x == (y < z)),因此它将成为

int c = MIN (x == (y < 1) ? x == y : 1)
Run Code Online (Sandbox Code Playgroud)

如果你使用第二个表达式...而且这是错误的,所以第一个表单更好.

让我们来试试吧#define MIN (A,B) ((A) < (B) ? (A) : (B))......

我们在这里

int c = MIN ((x == y) < (1) ? (x == y) : (1))
Run Code Online (Sandbox Code Playgroud)

好多了!

最后他们都"坏",因为

int c = MIN(++x, 1);
Run Code Online (Sandbox Code Playgroud)

++x进行两次评估(一次在<比较中,一次由三元运算符"选中"作为结果)

int c = MIN ((++x) < (1) ? (++x) : (1))
Run Code Online (Sandbox Code Playgroud)