c - 条件运算符在算术运算中的行为

标签 c gcc

这道题是关于条件运算符在算术运算和赋值语句中的作用。

在 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/

相关文章:

c++ - bool 到 int 的转换

C printf 到自定义硬件

c - 如果在这段代码中直接将变量 i 传递给线程会发生什么?

c - 警告 : comparison of unsigned expression >= 0 is always true

C++ 初始化列表 : using non-initialized members to initialize others gives no warning

c - 从 recvfrom : why? 收到错误地址

c - Varnish 4 + Pounds - 绕过特定 IP 地址的缓存

c - gcc 在我制作的静态库中找不到头文件

c++ - 如何使用gcc在centos 6.4中使用gcc64的旧版本进行编译

c++ - 使用 makefile 时如何禁用 GCC 优化?