+ 3

Explain the output pls

int x=1,y=1,z=1; cout<<(++x||++y&&++z); cout<<x<<y<<z; output is 1211 according to me output should be 1222

9th Jan 2018, 7:14 PM
Himani
10 ответов
+ 3
What I think happening here is "Short Circuit Evaluation". That means that the compiler doesnt necessarily tests all conditions, but rather stops as soon as he got what he requires (basically). Imagine this: In an AND-Operator, if the first condition is false, there is no need for the compiler to check the second one because first is false, so the expression cant get true anymore anyway. Same with OR-Operator: If a true condition is found, the overall expression must already be true. So in your case: The compiler recognizes the OR-Operator and evaluates that the first condition is true, therefore the overall expression becomes true without any need to check the AND-Statement since it doesnt matter at all whether it is false or true. As a result, y and z are not incremented, and 1211 is printed. https://code.sololearn.com/cK4fG82x6lhP/?ref=app
9th Jan 2018, 7:51 PM
Shadow
Shadow - avatar
+ 4
https://www.sololearn.com/discuss/988067/?ref=app
9th Jan 2018, 7:21 PM
emmey
emmey - avatar
+ 3
|| and && have the same priority. Change in your code the position of || and &&. You will see that x and y are increased
9th Jan 2018, 8:40 PM
I. Stark
I. Stark - avatar
+ 3
tysm everyone ☺ I have understood.
10th Jan 2018, 3:37 AM
Himani
+ 2
I still not get it first the && operator Will be tested as it has higher priority than ||operator , so there should be increment in y and z.
9th Jan 2018, 7:26 PM
Himani
+ 2
its a Boolean expression. It never finds a reason to even make it to &&. Evaluates true instantly and returns its value
9th Jan 2018, 7:45 PM
emmey
emmey - avatar
+ 2
Naitomeas answer is the reason for that behavior. Runtime Optimization, i think. Look at my example Jamols question. z is increased. For && both operands have to be true
9th Jan 2018, 8:13 PM
I. Stark
I. Stark - avatar
+ 2
But why it is not checking AND statement first?
9th Jan 2018, 8:30 PM
Himani