简体   繁体   English

C关系运算符输出

[英]C Relational Operator Output

#include <stdio.h>
void main()
{
    int x = 1, y = 0, z = 5;
    int a = x && y || z++;
    printf("%d", z);
}

This yields output as 6 whereas 这产生了6的输出

#include <stdio.h>
void main()
{
    int x = 1, y = 0, z = 5;
    int a = x && y && z++;
    printf("%d", z);
}

this would yield answer as 5. WHY ?? 这会产生答案为5.为什么? Someone please explain. 有人请解释一下。

This is due to the Short Circuit mechanism . 这是由于短路机制造成的

What this means is that when the result of a logical operator is already determined, the rest of the expression isn't evaluated at all, including potential side effects. 这意味着当已经确定逻辑运算符的结果时,根本不评估表达式的其余部分,包括潜在的副作用。

The first code fragment behaves like: 第一个代码片段的行为如下:

int a = (1 && 0) /* result pending... */ || z++;

And the second: 第二个:

int a = (1 && 0) /* result determined */;

This happens because the value of a logical AND is known to be false if the left side expression is false. 发生这种情况是因为如果左侧表达式为false,则逻辑AND的值已知为false。

As you can probably tell, the difference between two fragments of code is that the first one evaluates z++ , while the other one doesn't. 正如您可能知道的那样,两个代码片段之间的区别在于第一个代码片段评估z++ ,而另一个代码片段没有。

The reason the second code does not evaluate z++ is that the expression ahead of it evaluates to false , so && chain "short-circuits" the evaluation of the last term. 第二个代码不评估z++是它前面的表达式的计算结果为false ,因此&& chain“短路”最后一个术语的评估。

Operator || 运营商|| , on the other hand, would short-circuit only when the left side is true . 另一方面,只有在左侧为true时才会短路。

For starters function main without parameters shall be declared like 对于启动器,没有参数的函数main应声明为

int main( void )

In the first program the initialization expression can be represented like 在第一个程序中,初始化表达式可以表示为

int a = ( x && y ) || ( z++ );

According to the C Standard (6.5.14 Logical OR operator) 根据C标准(6.5.14 Logical OR运算符)

  1. ...If the first operand compares unequal to 0 , the second operand is not evaluated. ...如果第一个操作数比较不等于0 ,则不计算第二个操作数。

The first oerand ( x && y ) of the expression is equal to 0 because y is initialized by 0 表达式的第一个oerand ( x && y )等于0,因为y初始化为0

int x = 1, y = 0, z = 5;

So the second operand ( z++ ) is evaluated. 因此评估第二个操作数( z++ )

As result z will be equal to 6. 结果z将等于6。

In the second program the initialization expression can be represented the same way as in the first program 在第二个程序中,初始化表达式可以用与第一个程序相同的方式表示

int a = ( x && y ) && ( z++ );

According to the C Standard (6.5.13 Logical AND operator) 根据C标准(6.5.13逻辑AND运算符)

  1. ...If the first operand compares equal to 0 , the second operand is not evaluated. ...如果第一个操作数比较等于0 ,则不计算第二个操作数。

As before the first operand ( x && y ) of the expression is equal tp 0 and according to the quote the second operand ( z++ ) is not evaluated. 与之前一样,表达式的第一个操作数( x && y )等于tp 0,并且根据引用,不计算第二个操作数( z++ )

As result z will be equal to 5 as before. 结果z将像以前一样等于5。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM