Output of C++ Program | Set 20

Predict the output below program

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


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:-

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


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!

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


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.



My Personal Notes arrow_drop_up


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.