在三元运算符的第一个表达式中如何处理赋值运算符?

How is the assignment operator treated in the first expression of the ternary operator?

如果我在下面代码的三元运算符的第一个表达式中给出一个等于关系运算符,那么它输出10 ,20,这个我理解了

#include <stdio.h>

int main()
{
    int a=10, c, b;
    
    c = (a==99) ? b = 11:20;
    
    printf("%d, %d", a, c);

    return 0;
}

但是,当我放置一个 Assignment 运算符而不是 Equal to 关系运算符(代码在下面给出)时,它会输出99、11。现在我不知道如何在三元运算符的第一个表达式中处理这个 Assignment 运算符。

#include <stdio.h>

int main()
{
    int a=10, c, b;
    
    c = (a=99) ? b = 11:20;
    
    printf("%d, %d", a, c);

    return 0;
}

a=99 是对值 99 的变量 a 的赋值。 99 在 C 中为真,因此变量 cb 在您的第二个程序中都被赋值为 11

赋值运算符将变量 a 设置为 99,任何大于零的值都为真,因此它 returns 为真并将变量 c 设置为 11。

这一行

c = (a==99) ? b = 11:20;

做的一样
if (a == 99)
{
    c = b = 11;
}
else
{
    c = 20;
}

这条线也是如此

c = (a=99) ? b = 11:20;

做的一样
if (a = 99)
{
    c = b = 11;
}
else
{
    c = 20;
}

有趣的部分是

if (a = 99)
{
    ...

执行对 a 的赋值,然后检查分配的值是零 (false) 还是非零 (true)。所以可以写成:

a = 99;
if (a != 0)
{
    ...

顺便说一句:if (a != 0)也可以写成if (a)