Logical operations in cout (C++)

落花浮王杯 提交于 2019-12-08 09:01:36

问题


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.



来源:https://stackoverflow.com/questions/26952726/logical-operations-in-cout-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!