0

I was trying c programming and I wrote a small code but I am unable to understand this

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

    int x,y,z,k;
    x=y=z=k=1;

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

I was expecting output as 2 1 1 2 because the precedence of && is more than || but the output is 2 1 1 1 please explain.

hello123
  • 391
  • 4
  • 15

1 Answers1

5

C uses short-circuit evaluation, so when x++ is evaluated as true, the remaining expressions are not evaluated, and no increment occurs.

MooseBoys
  • 6,641
  • 1
  • 19
  • 43
  • but the priority of && is more then || so both (x++||y++) and k++ should be evaluated, i agree y++ will not be done because x++ is true but k++ should be done right? – hello123 Jan 29 '15 at 16:29
  • Nope. It's enough that `x++` evaluates to `true`. No need to do anything with the right hand part of `||`. This answer is correct. – Bathsheba Jan 29 '15 at 16:30
  • @maneeshbhunwal; Read this [answer](http://stackoverflow.com/a/17432858/2455888) – haccks Jan 29 '15 at 16:31
  • See also [this duplicate question](http://stackoverflow.com/questions/3375041/please-explain-an-apparent-conflict-between-precedence-of-and-and-the-actu) – Paul R Jan 29 '15 at 16:32