Output of C++ Program | Set 19

Predict the output below program

#include<iostream>
using namespace std;
int main()
{
    int x = 1 , y = 1, z = 1;

    cout << (++x || ++y && ++z ) << endl;  

    cout << x << " " << y << " " << z ;          

    return 0;
}

Explanation:-
It is based on fact that how LOGICAL – OR and LOGICAL-AND work. Note that Compiler reads OR and AND operators from left to right. Let us take the following cases into consideration:-

#include<iostream>
using namespace std;
int main()
{
    int x = 1 , y = 1;
    cout << ( ++x  || ++y ) << endl;   // outputs 1;
    cout << x << " " << y;             // x = 2 , y = 1;
    return 0;
}

Output:

1
2 1

Once compiler detects “true” on the LEFT of logical OR, IT IS NOT GOING TO EVALUATE THE RIGHT SIDE!, because even one is true, the whole “OR” expression becomes true!. SO compiler skips the RIGHT part and displays the result as 1 !So y is not incremented here , because compiler skipped reading it!

#include<iostream>
using namespace std;
int main()
{
    int x = 1 , y = 1;
    cout << ( ++x && ++y ) << endl;     //outputs 1;
    cout << x << " " << y;              // x = 2 , y = 2;
    return 0;
}

Output:

1
2 2

LOGICAL AND needs to evaluate both right and left part (Think about it !)So both left and right part is evaluated, thus incrementing both x and y here.

#include<iostream>
using namespace std;
int main()
{
    int x = 1 , y = 1, z = 1;
    cout << ( ++x || ++y && ++z ) << endl;    //outputs 1;
    cout << x << " " << y << " " << z ;       //x = 2 , y = 1 , z = 1;
    return 0;
}

Output:

1
2 1 1

Here compiler increments x first and then it detects a LOGICAL OR. We have a true quantity on left side . SO compiler won’t read the right part.Thus incrementing x and y,z remains same!

This article is contributed by Nishant .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice





Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.