x &= foo() // We expect foo() be called whatever the value of x
但是,操作符 &&=和 ||=将是逻辑的,并且这些操作符可能容易出错,因为许多开发人员希望 foo()总是在 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
我们真的需要让 C/C + + 变得更复杂来获得 x = x && foo()的快捷方式吗?
难道我们真的要混淆更多的神秘语句 x = x && foo()?
或者我们想要编写像 if (x) x = foo();这样有意义的代码?
答案很长
例如 &&=
如果 &&=操作符可用,则该代码:
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
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 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();