I was solving the C++ Multiple choice questions.
I am not able to understand the output for the following code::
#include <iostream>
using namespace std;
int main()
{
int x,y,z;
x=y=z=1;
z=++x || ++y && ++z;
cout<<x<<" "<<y<<" "<<z<<endl;
system("pause");
return 0;
}
I am solving this question in following way::
Precedence order ::
Precedence "++" greaterthan Precedence "&&" greaterthan Precedence "||"
Also , the Associativity of unary++ is “Right to left”
.
So
z=(++x)||(++y) && (2)
z=(++x)||(2)&& (2)
z=(2)||(2)&&(2)
z=(2)|| 1 //As 2 && 2 is 1(true)
z=1 // As 2 || 1 is 1(true)
So as per me ,the correct output should be x=2,y=2 and z=1.
But When i ran this code in my compiler,the compiler output is x=2,y=1,z=1.
Why i am getting such output and where i am making mistake?
Thanks!
Operator precedence tells you how to group expressions; it doesn’t tell you in which order they are executed.
||and&&are special in that the first operand is always evaluated first and the second operand (including all sub-expressions) is only evaluated if it is required to determine the value of the expression.For
||, if the first operand evaluates totruethe second operand is not evaluated because the result of the logical-or will always be true.Similarly, the second operand of
&&will not be evaluated if the first operand evaluates to false as the logical-and must be false in this case.In the expression
z=++x || ++y && ++z, the grammar rules specify a grouping:In the sub-expression
(++x) || ((++y) && (++z)), as(++x)evaluates totrue(as 2 is non-zero), the second operator((++y) && (++z))is never evaluted.xbecomes 2,yis unchanged andzis assigned1(trueconverted to an integer).