Reputation: 151
OK so obviously this question might sound dumb for more experienced people, but, for the following lines the result I get is 0:
int x = 2,
y = -2;
cout << (x++ - y && (--x + y));
I understand it means that either one of these two expressions equals 0, but how? As far as I understand, this should be (3 && -1)?
Also, a little subquestion: when does x++ exactly take effect? On the next occurance of x within the same expression, after the left-shift operator within the same line, or in the next statement?
Thank you!
Upvotes: 1
Views: 111
Reputation: 44258
As far as I understand, this should be (3 && -1)?
you understand wrong:
first left side is fully evaluated, as it is necessary for short circuit evaluation with logical and
(details can be found here)
x++ - y == 4 // as result of x++ == 2 so (2-(-2)), after that x == 3
result is true
so right side is evaluated:
--x + y == 0 // as result of --x == 2 so (2+(-2)), after that x == 2
result on the right is false
so result of and
is false
as well which printed by std::ostream
as 0
Note: short circuit evaluation of logical or
and and
operations make such code valid (making them sequenced) but you better avoid such questionable expressions. For example simple replacing logical and
to binary would make it UB.
Upvotes: 4