Open In App

Output of C++ Program | Set 20

Improve
Improve
Like Article
Like
Save
Share
Report

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!



Last Updated : 04 May, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads