+ 3
Why the output is 1211? How do we get 1 for the first output and why the values of y and z didn't change to 2?
#include <iostream> using namespace std; int main() { int x=1, y=1, z=1; cout<<(++x||++y&&++z); cout<<x<<y<<z; return 0; }
9 Réponses
+ 7
First off, the order of execution is NOT the same as the order of evaluation. What does that mean is, even though the precedence of logical AND operator is higher than the OR operator, the evaluation process doesn't care much about that. To explicitly specify the order of evaluation (and make it clearer for eye and mind) you can do something like this
(++x) || (++y && ++z)
Much better, right?
Now, the order of eval is becoming more obvious. As a note for || operator, As long as the left hand operand is true (which in this case is true) there is no need to right hand operand gets evaluated and as a result you got the right output after the process gets done.
+ 4
Liza
When it reaches to zero. maybe something like this
(--x)
Then, the eval process checks the right hand of the thing. If it was true, then the output will still be true for the first output but the whole result would be different.
+ 4
Ishaq Ezekiah
Sure enough the output stream just sees the ++x and throw away the rest. That's why you must bind the evaluations in a pair of parenthesis. Another one is this
cout << true ? "foo" : "bar";
and guess what, the screen shows you 1 just because of the absence of parenthesis.
+ 4
K Locher
+1 for "short circuit" technicality. ;-]
+ 3
Liza
The kewords are: operator precedence, associativity and short circuit evaluation.
1. Due to left-to-right associativity the OR is evaluated at first and cos not equal to 0, it is true.
2. The term in paranthesis is already true to for sure, the evaluation of the remaining term is aborted (short circuit evaluation)
3. The boolean value ‘true’ causes the first ‘1’ in the printout.
4. The x is 2 after the increment, the y and z were not changed (remember the short circuit eval) and thus are both ‘1’.
+ 2
Ishaq Ezekiah
This is because the first output is the incremented x (the remaining term is not evaluated because of short circuit evaluation).
The 2nd output is the boolean value ‘true’ which is internally casted to its int-representation -> ‘1’.
+ 1
This question is blowing my mind..
cout << ++x||++y&&z ;
//output is 2
but
cout <<(++x||++y&&z);
//output is 1
what are those parenthes do actually?
Thats is the reason you got 1 as a first value.. but i dont understand how it works, with and without parenthes
0
In this case when the left operand (++x) can be false?
0
Thanks.. now i know the short circuit terms, i do get a parentheses warning in build log.
which mean || cant be put together with && in single parentheses