【问题标题】:Behavior of Conditional Operator in arithmetic operation条件运算符在算术运算中的行为
【发布时间】: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”。

标签: c gcc


【解决方案1】:

t2 的值取决于模数%、加法+ 和三元?: 运算符的运算符优先级。

您可以通过this 链接找到完整的 C 运算符优先级列表。

在您的情况下,模运算符具有最高优先级,其次是加法,然后是三元运算符。

【讨论】:

  • @ChinmayJoshi,如果您对我的回答感到满意,请接受:)
【解决方案2】:

案例 1:int t2=temp%100 + temp&gt;99?2000:1900; 为清晰起见重写为:int t2=(temp%100 + temp)&gt;99 ? 2000 : 1900;

而那个表达式:temp%100 + temp 是 140,大于 99,所以这个表达式的值是 2000


案例2:int t2=temp%100 + (temp&gt;99?2000:1900);

temp不是GreaterThan 99,所以表达式是1900,加上temp%100,得到1970


案例3:int t2= temp&gt;99?2000:1900 +temp%100;

temp不大于99,所以表达式为1900+70,结果为1970


这是所有操作顺序;正如*/ 优先于+-,所有运算符都有优先级。

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 2022-07-07
    • 1970-01-01
    • 2016-08-08
    • 2013-05-10
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多