Logical operations in cout (C++)

2019-06-10 20:59发布

问题:

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

回答1:

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).



回答2:

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.



标签: c++ cout