在leetcode刷题LeetCode C 实现110. Balanced Binary Tree时有如下两个宏:

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

在编写代码时我写成了后者,在检查了代码之后提交始终失败,gdb调试时发现max这个宏存在问题。
1 + max(a, b)
相当于:
1 + ((a) > (b))?(a):(b)
考虑运算符优先级+大于?:,从右到左,因此相当于
(1 + ((a) > (b))) ? (a) : (b)
由于(1 + ( (a)> (b) )始终大于零,所以该宏始终输出a
验证程序:

#include <stdio.h>
#define max(a,b) ((a) > (b))? (a):(b)
int test(int a,int b)
{
    return 1+max(a,b);
}
int main()
{
    printf("%d\n",test(1,2));
    printf("%d\n",test(3,2));
    printf("%d\n",test(7,2));
    printf("%d\n",test(-1,2));
    printf("%d\n",test(8+8,2));

    return 0;
}

执行结果:
1
3
7
-1
16

另一种存在错误的应用场景是:
max(a, b) * 2
相当于:
((a) > (b))?(a):(b) * 2

((a) > (b))?(a):((b) * 2)
如果此时a>b,本来的目的是要返回2*a结果返回的是a.
验证程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

int main()
{
    printf("%d\n",max(3,2)*2);
    return 0;
}

程序输出:
3