Programming Tips - C/C++: Update a bool result that involves a series of steps

Date: 2014sep19 Update: 2026oct2 Language: C/C++ Q. C/C++: 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. Full Example Use:
#include <stdio.h> bool step1() { printf("%s returning true\n", __FUNCTION__); return true; } bool step2() { printf("%s returning false\n", __FUNCTION__); return false; } bool step3() { printf("%s returning true\n", __FUNCTION__); return true; } // (Place doSteps() from above here) int main() { bool result = doSteps(); printf("result from doSteps() is %s\n", result ? "true" : "false"); }
Output:
step1 returning true step2 returning false step3 returning true result from doSteps() is false
As you can see, all 3 steps are done. Since one step returns false, doSteps() returns false (which is exactly whats wanted).