Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

c/c++ 三目运算符的一个疑问

刚刷leetcode 104,遇到一个奇怪的问题,总结起来就是如下代码:

#include <stdio.h>
int main()
{
    int m = 2;
    int n = 10;
    int x = 1 + (m > n) ? m :n;
    printf("%d
",x);
    return 0;
}

int x = 1 + ((m > n) ? m :n);
这个写法和上面写法得到的结果不同,+运算符优先级高于 ?,这种现象怎么解释?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

+运算符优先级高于 ?,把三目条件写在一块就好,int x = 1 + (m > n ? m :n);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...