简短答案
所有的运营商+=
,-=
,*=
, /=
,&=
,|=
...是算术,并提供同样的期望:
x &= foo() // We expect foo() be called whatever the value of x
但是,运算符&&=
和||=
是合乎逻辑的,并且这些运算符可能容易出错,因为许多开发人员希望foo()
总是调用in x &&= foo()
。
bool x;
// ...
x &&= foo(); // Many developers might be confused
x = x && foo(); // Still confusing but correct
x = x ? foo() : x; // Understandable
x = x ? foo() : false; // Understandable
if (x) x = foo(); // Obvious
长答案
范例 &&=
如果&&=
运算符可用,则此代码:
bool ok = true; //becomes false when at least a function returns false
ok &&= f1();
ok &&= f2(); //we may expect f2() is called whatever the f1() returned value
等效于:
bool ok = true;
if (ok) ok = f1();
if (ok) ok = f2(); //f2() is called only when f1() returns true
第一个代码容易出错,因为许多开发人员会认为f2()
无论f1()
返回的值是什么,它总是被称为。就像写只有在返回时才被调用的bool ok = f1() && f2();
地方。f2()
f1()
true
- 如果开发者实际想
f2()
要调用只有当f1()
返回true
,因此,第二代码是以上更不易出错。
- 否则(开发人员
f2()
总是被要求致电)&=
就足够了:
范例 &=
bool ok = true;
ok &= f1();
ok &= f2(); //f2() always called whatever the f1() returned value
而且,编译器优化上面的代码比下面的代码更容易:
bool ok = true;
if (!f1()) ok = false;
if (!f2()) ok = false; //f2() always called
比较&&
并&
我们可能想知道将运算符&&
和&
应用于bool
值时是否给出相同的结果?
让我们使用以下C ++代码进行检查:
#include <iostream>
void test (int testnumber, bool a, bool b)
{
std::cout << testnumber <<") a="<< a <<" and b="<< b <<"\n"
"a && b = "<< (a && b) <<"\n"
"a & b = "<< (a & b) <<"\n"
"======================" "\n";
}
int main ()
{
test (1, true, true);
test (2, true, false);
test (3, false, false);
test (4, false, true);
}
输出:
1) a=1 and b=1
a && b = 1
a & b = 1
======================
2) a=1 and b=0
a && b = 0
a & b = 0
======================
3) a=0 and b=0
a && b = 0
a & b = 0
======================
4) a=0 and b=1
a && b = 0
a & b = 0
======================
结论
因此是我们可以更换&&
用&
的bool
值;-)
所以最好使用&=
代替&&=
。对于布尔值,
我们可以认为&&=
是无用的。
相同的 ||=
操作者|=
也不太容易出错比||=
如果开发者想f2()
被称为只有当f1()
收益false
,而不是,:
bool ok = false;
ok ||= f1();
ok ||= f2(); //f2() is called only when f1() returns false
ok ||= f3(); //f3() is called only when f1() or f2() return false
ok ||= f4(); //f4() is called only when ...
我建议以下更容易理解的替代方案:
bool ok = false;
if (!ok) ok = f1();
if (!ok) ok = f2();
if (!ok) ok = f3();
if (!ok) ok = f4();
// no comment required here (code is enough understandable)
或者,如果您更喜欢一种线条样式:
// this comment is required to explain to developers that
// f2() is called only when f1() returns false, and so on...
bool ok = f1() || f2() || f3() || f4();