cout中的逻辑运算(C ++) [英] Logical operations in cout (C++)
问题描述
考虑:
int i = 56, j = 0;
int n = i&&j;
cout << i&&j;
cout << endl << n;
输出将是:
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
推荐答案
表达式 cout<< i& j
等效于(cout<< i)&& j
。这两个操作数都将求值并转换为 bool
。该语句整体上没有任何作用,但是对子表达式 cout<<的求值是无效的。 i
具有通常的副作用,即向标准输出中写入内容。
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.
&& ;
运算符确实是短路的,并且仅在 cout<<<时才评估
的评估结果为 j
。 i true
。此条件等效于 cout.good()
,通常是这种情况(除非您以某种方式设法关闭了标准输出)。
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).
这篇关于cout中的逻辑运算(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!