这道题是关于条件运算符在算术运算和赋值语句中的作用。
在 gcc、arm-gcc 上测试。
//gcc 5.4.0
#include <stdio.h>
int main(void)
{
printf("Hello, world!\n");
int temp=70;
int t2=temp%100 + temp>99?2000:1900;
printf("t2=%d",t2);
return 0;
}
//This code returns answer 2000.
//gcc 5.4.0
#include <stdio.h>
int main(void)
{
printf("Hello, world!\n");
int temp=70;
int t2=temp%100 + (temp>99?2000:1900);
printf("t2=%d",t2);
return 0;
}
//This code returns answer 1970.
//gcc 5.4.0
#include <stdio.h>
int main(void)
{
printf("Hello, world!\n");
int temp=70;
int t2= temp>99?2000:1900 +temp%100;
printf("t2=%d",t2);
return 0;
}
// Answer is 1970
//gcc 5.4.0
#include <stdio.h>
int main(void)
{
printf("Hello, world!\n");
int temp=70;
int t2= 5+ temp>99?2000:1900 +temp%100;
printf("t2=%d",t2);
return 0;
}
// Answer is, 1970!
一旦算术语句遇到条件运算,它会忽略语句的左边部分。 (我认为按执行顺序执行条件操作后的任何内容都将被忽略)
此外,我们可以通过使用圆括号 () 或在最左侧进行条件运算来缓解这种情况。 谁能解释这种行为?在算术语句中使用条件运算是否会引入未定义行为问题?
也很惊讶以前没有人问过这个问题。如果是,请提供链接。 非常感谢!
最佳答案
t2
的值取决于模数 %
、加法 +
和三元 ? 的运算符优先级:
运算符。
您可以通过关注 this 找到 C 运算符优先级的完整列表链接。
在您的情况下,模数运算符具有最高优先级,其次是加法,然后是三元运算符。
关于c - 条件运算符在算术运算中的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54203290/