为什么这个程序输出8?

Why does this program output 8?

#include <stdio.h>
#define abs(x) x > 0 ? x : -x

int main(void) {
  printf("%d\n", abs(abs(3 - 5)));
  return 0;
}

为什么上面的程序输出8而不是2,而下面的程序输出2?

#include <stdio.h>

int abs(int x) {
  return x > 0 ? x : -x;
}

int main(void) {
  printf("%d\n", abs(abs(3 - 5)));
  return 0;
}

简答为 "because a macro is not a function"。

长答案是宏参数被扩展到程序的文本中,所以C编译器看到这个长表达式:

3 - 5 > 0 ? 3 - 5 : -3 - 5 > 0 ? 3 - 5 > 0 ? 3 - 5 : -3 - 5 : -3 - 5 > 0 ? 3 - 5 : -3 - 5

在扩展中,负号适用于 3,不适用于 (3-5),产生负数 8。

尽管您可以通过在宏定义中将 x 括起来来解决此问题,但定义内联函数将是更好的选择。