简体   繁体   English

解释c程序的输出

[英]Explain the output of the c program

#include<stdio.h>
void main(){

int x,y,z;
x=y=z=1;
z=++x||++y&&++z;
printf("%d %d %d \n",x,y,z);
getch();
}

the output is coming as 2 1 1 ! 输出为2 1 1! i'm not able to get why...if we go by the precedence of the operators this can't be explained. 我不知道为什么...如果我们以运算符的优先顺序去做,这是无法解释的。 Please help 请帮忙

Logical or ( || ) introduces a sequence point. 逻辑or|| )引入一个序列点。 Its left side is evaluated. 评估其左侧。 Then, if and only if that produced 0/false, the right side is evaluated. 然后,当且仅当产生0 / false时,才评估右侧。

In this case, ++x comes out to 2, so the right side is never evaluated. 在这种情况下, ++x等于2,因此永远不会评估右边。 That, in turn, means y and z remain as 1 . 这又意味着yz保持为1

The || || operator short-circuits. 操作员短路。 The left-hand operand is evaluated first, and if it evaluates to non-zero, the right operand is never computed. 首先评估左侧操作数,如果评估结果为非零,则永远不会计算右侧操作数。 This also prevents side-effects of evaluation of the right operand. 这也防止了对正确操作数求值的副作用。

When you use an || 使用||时 operator, if the LHS turns out to be true, the end result is true. 运算符,如果LHS结果为true,则最终结果为true。 So, it does ++x which turns out to be 1 and the final result is ++x = 2 and z = 1 & y = 1 因此,它确实是++ x,结果为1,最终结果是++ x = 2和z = 1&y = 1

The boolean || 布尔|| short circuits. 短路。 That is once it finds a true value it stops evaluating. 那就是一旦它找到一个真实值,它就会停止评估。 Thus all that happens in the z assignment x incremented and z is set to one then 因此,z赋值x中发生的所有事情都递增,并且z设置为1,然后

Addendum to above answers: 上述答案的附录:

In C/C++ , these operators are the short-circuit operators viz., '&&', '||' 在C / C ++中,这些运算符是短路运算符,即'&&','||' and '?'(conditional operator). 和'?'(条件运算符)。

Do yourself a favor and check out this excellent wiki page on Short-circuit evaluation . 请帮个忙,并查看有关短路评估的出色Wiki页面 Don't miss the Common usage section of the article. 不要错过本文的“ 常用用法”部分。

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

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