Consider:
int i = 56, j = 0;
int n = i&&j;
cout << i&&j;
cout << endl << n;
the output would be:
56
0
I imagine its either because of operator precedence or logical short circuit, but I can't seem to figure out which or the reason
The expression cout << i&&j
is equivalent to (cout << i) && j
. Both operands are evaluated and converted to bool
. The statement as a whole has no effect, but the evaluation of the subexpression cout << i
has the usual side effects, of course, namely writing something to the standard output.
The &&
operator is indeed short-circuited and j
is only evaluated if cout << i
evaluates as true
. This condition is equivalent to cout.good()
, which is usually the case (unless you somehow managed to close your standard output).
As you expected, the <<
operator comes takes precedence over &&
.
Thus, cout << i&&j
first outputs i, then compares the returned stream to j (both are true, so the returned value is true, but this value is discarded).
See here for the full list of operator precedence.