Date: 2014sep19
Language: C/C++
Q. How can update a bool result that involves a series of steps?
A. One way is:
bool doSteps() {
bool result = true;
if (!step1()) result = false;
if (!step2()) result = false;
if (!step3()) result = false;
return result;
}
That works but isn't so pretty.
You might think you can and it all together like this:
bool doSteps() {
return step1() && step2() && step3(); // WRONG
}
But this is wrong because C/C++ might not do all the steps (shortcutting).
I think the nicest way is:
bool doSteps() {
bool result = true;
result &= step1();
result &= step2();
result &= step3();
return result;
}
The calls to the steps are cleaner.
But, &= is a bitwise operator you might say (and we want a logical operator here). Turns out &= does the same as &&= (if it existed) here.
This also works in Java.