tortuga
tortuga

Reputation: 757

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 ! i'm not able to get why...if we go by the precedence of the operators this can't be explained. Please help

Upvotes: 1

Views: 1139

Answers (5)

epiphany27
epiphany27

Reputation: 517

Addendum to above answers:

In C/C++ , these operators are the short-circuit operators viz., '&&', '||' and '?'(conditional operator).

Do yourself a favor and check out this excellent wiki page on Short-circuit evaluation. Don't miss the Common usage section of the article.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490048

Logical or (||) introduces a sequence point. Its left side is evaluated. Then, if and only if that produced 0/false, the right side is evaluated.

In this case, ++x comes out to 2, so the right side is never evaluated. That, in turn, means y and z remain as 1.

Upvotes: 6

Hogan
Hogan

Reputation: 70513

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

Upvotes: 1

Sujay
Sujay

Reputation: 6783

When you use an || operator, if the LHS turns out to be true, the end result is true. So, it does ++x which turns out to be 1 and the final result is ++x = 2 and z = 1 & y = 1

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283624

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.

Upvotes: 3

Related Questions