【发布时间】:2019-01-15 16:45:25
【问题描述】:
这个问题是关于条件运算符在算术运算和赋值语句中的工作原理。
在 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!
一旦算术语句遇到条件运算,它就会忽略语句的左边部分。 (我认为条件操作后按执行顺序的任何内容都会被忽略)
此外,我们可以通过使用圆括号 () 或在最左侧进行条件操作来缓解这种情况。 谁能解释这种行为?在算术语句中使用条件运算是否会引入任何未定义的行为问题?
也很惊讶以前没有问过这个问题。如果是,请提供链接。 非常感谢!
【问题讨论】:
-
“圆括号”,我喜欢它!你刚刚在我的词汇表中添加了一个新词:)
-
三元运算符遵循标准operator precedence and associativity,与任何其他运算符一样。
-
它们被称为“括号”,或简称为“parens”。