0

I am trying following C code. I my opinion output of this code should be 0 0 0 0. But after executing it output comes as 0 -1 -1 0. Can anybody explain how output comes.

    #include<iostream>
    using namespace std;
    int main()
    {
        int x=-1, y=-1, z=-1;
        int w= ++x && ++y && ++z;
        cout<<x<<" "<<y<<" "<<z<<" "<<w<<endl;
        return 0;
    }
krishna
  • 25
  • 4

1 Answers1

3

This is because of the short-circuit behaviour of the && operator. ++x evaluated to 0 which will be considered as false. So, only ++x will be evaluated and rest expressions will not be evaluated and final value of the expression ++x && ++y && ++z will be 0 and it will be assigned to w.

haccks
  • 104,019
  • 25
  • 176
  • 264