# Explain C++ code

There is a C++ challenge with the following code: int x=1,y=1,z=1; cout << (++x || ++y && ++z); cout << x << y << z; Thre result is 1211. First '1' is from the first cout and therefore: x = 2 y = 1 z = 1 I know that for an OR expression such as (++x || ++y), if the first term is true then there is no need to evaluate the second. This leads to x=2 and y=1. But how about the AND expression? Why is z not set to 1? Does z not getting evaluated?

6/25/2018 5:57:46 AM

Adam Aksu18 Answers

New Answerz is not getting evaluated because it looks like this: ++x || (++y && ++z) since && has higher precedence than ||

this reminds me of some groovy code where I was evaluating the Boolean return of a function before the simpler variable check and it slowed things down significantly... to illustrate: (someBoolFunction()||x==5) vs (x==5||someBoolFunction())

Aaah got it. Assumed same precedence. So it boils down to an OR expression.. Thank you Max && Udi Finkelstein !

Saurav Priyadarshi it is not x that is printed but the result (true, I.e. 1) of the logical expression within parentheses.

You got it 99% correct. The missing 1% you missed is that due to operator precedence, the && operator has a higher precedence than || and therefore, The right hand side of the || expression, which as you said yourself, is not evaluated (because the 1st part is already true) includes the entire '++y && ++z' expression.

The operator precedence is not necessarily the same thing as order of execution (evaluation). As a result, the above line can be explicitely reform as follow for clarifying the evaluation order ( ++x || (++y && ++z)) Once left side of || being evaluted to true, the right side (as you aware) is discarded.

Vulture With Loveness☺️☺️ are you asking about my previous comment about || ? It was just in response to a question from Petest Sam about meaning of the double pipe symbol.

Petest Sam it is the logical or. expression || expression is true if at least one of them is true

Saurav Priyadarshi because the result lf the logical operation is true and true gets cast to 1 for printing

Petest Sam As Max mentioned, the expected result from a logical OR operation is pretty much straight forward. Note that any non-zero value is considered true or 1 when doing evaluation. ~example~ int x = 31; int y = 0; int z = -1; bool b1 = x || y; // true bool b2 = x || z; // true bool b3 = y || y; // false

Why is 1 not 2 printed in the beginning? Since we can see that prefix increment is applied on x, so x should be incremented before being printed.

Saurav, because of the OR/AND operators, the term inside the brackets gets evaluated to a bool, with a value of true this is output as 1.

There you need precidence bro as you know that the higher precidence operator is %. As here the &&op is the higher orecidence then the ||op.