这个问题在这里已经有了答案:
Is short-circuiting logical operators mandated? And evaluation order?
(7 个回答)
2年前关闭。
我总是不敢这样编码:
void func( some_struct* ptr ) {
if ( ptr != nullptr && ptr->errorno == 0 )
do something...
};
相反,我总是这样做:
void func( some_struct* ptr ) {
if ( ptr != nullptr )
if ( ptr->errorno == 0 )
do something...
};
因为我担心逻辑运算符 && 的评估顺序在 C++ 标准中是未指定的,即使通常我们可以使用几乎所有当今的编译器得到正确的结果。
在 a book , 2 条规则让我想确切地了解它。
我的问题是:
不重载,是逻辑运算符“&&”和“||”的求值顺序定?
对不起我丑陋的英语,我是中国人。如果有重复的主题,我深表歉意,因为我无法找出正确的关键字来搜索。
不管怎么说,还是要谢谢你!
最佳答案
是的,标准保证内置逻辑 AND 运算符和逻辑 OR 运算符。
(强调我的)
[expr.log.and]/1
The && operator groups left-to-right. The operands are both contextually converted to bool. The result is
true
if both operands aretrue
andfalse
otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand isfalse
.
[expr.log.or]/1
The || operator groups left-to-right. The operands are both contextually converted to bool. The result is
true
if either of its operands istrue
, andfalse
otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates totrue
.
关于c++ - c++ 标准是否指定了运算符&&(内置)的评估顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58897454/