为什么在 C 语言中 f(0) + f(11) == f(0) 通过条件定义 f(0)

OlW*_*OlW 5 c

#include<stdio.h>
#define f(x) (x<10) ? 1 : 3

int main(){
    int i = f(1) + f(11);
    printf("%d", i);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么在这种情况下,程序输出“1”而不是“4”。
定义宏的这两种不同用途究竟是如何工作的?

Yun*_*sch 10

查看编译器在预处理完成时看到的内容,()为了清楚起见添加了一些内容:

#include<stdio.h>

int main(){
    int i = (1<10) ? 1 : (3 + (11<10) ? 1 : 3);
    printf("%d", i);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

()我添加它们的原因可以在这里阅读:https :
//en.cppreference.com/w/c/language/operator_precedence

它表明?:优先级较低,并且+正在影响第一:部分评估的结果。

现在应该清楚了。

解决方案是()在宏定义中大量使用。
评论和其他答案已经提供了,我重复一遍:

#define f(x) (((x)<10) ? 1 : 3)
Run Code Online (Sandbox Code Playgroud)

我似乎()比其他提议还要多。
我的还可以防止有趣的事情,例如f(12||12)f(0&&0)行为怪异。