0

In the following code:

#include<iostream>
using namespace std;
int main()
{
    int x = 1 , y = 1, z = 1;
    cout << ( ++x || ++y && ++z ) << endl; //outputs 1;
    cout << x << " " << y << " " << z ;  //x = 2 , y = 1 , z = 1;
    return 0;
}

According to me, logical AND should evaluate first, followed by logical OR. However, the results seem to be contrasting my assumption. Can someone explain?

  • 3
    Have, you considered that `||` is short-circuit? If `a` in `a || (b && c)` is `true`, the second expression isn't evaluated whatever it contains. – Scheff's Cat Jun 28 '21 at 06:43
  • But why would the concept of short circuit work, I mean, doesn't arithmetic work according to precedence rules? @Scheff'sCat – loveofprogramming Jun 28 '21 at 06:45
  • 1
    Better than "according to me" (which may or may not be correct), cite a source like: https://en.cppreference.com/w/cpp/language/operator_precedence – sweenish Jun 28 '21 at 06:46
  • Does this answer your question? [Printing different values for ++i||j++&&++k with printf vs cout](https://stackoverflow.com/questions/68103350/printing-different-values-for-ijk-with-printf-vs-cout) – phuclv Jun 28 '21 at 06:59

3 Answers3

4

The operators || and && are short-circuit (if not overloaded).

Hence, for ||: if the first argument is true, the second is not evaluated.

For &&: if the first is false, the second is not evaluated.

If a in a || (b && c) is true, the second expression isn't evaluated whatever it contains.

(I set parentheses (which are actually not necessary) to emphasize what the 2nd argument of || is.)

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
2

operator&& has higher precedence than operator||, that means ++x || ++y && ++z will be interpreted as ++x || (++y && ++z), which doesn't mean (++y && ++z) gets evaluated firstly. ++x is still evaluated firstly, it gives a non-zero value which could convert to bool with value true, then (++y && ++z) won't be evaluated due to short-circuit evaluation.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
0

You seem to be confusing the precedence of an operator with order of evaluation. Yes, && has higher precedence than ||, so ++x || ++y && ++z is evaluated as ++x || (++y && ++z), but it's still evaluated from left to right.

See also Order of evaluation:

  1. Every value computation and side effect of the first (left) argument of the built-in logical AND operator && and the built-in logical OR operator || is sequenced before every value computation and side effect of the second (right) argument.

That is, the left argument of || will always be evaluated before the right argument. Thus ++x is evaluated first, this yields true and the condition short-circuits, so (++y && ++z) isn't evaluated at all.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30