Today I learned about eager boolean evaluation. In the following example, Bar()
will be evaluated even when Foo()
is true.
if (Foo() | Bar())
This answer on SO has an example:
if ((first = (i == 7)) & (second = (j == 10))) { //do something }
The use-case here would be that you want to reuse the results, but I would rather write it like this then:
first = (i == 7);
second = (j == 10);
if (first && second) { //do something }
Another use-case would be that Bar()
has a side-effect that should be executed regardless of Foo()
being true or false. Question is, can that be good code or would it indicate a code smell?
if
, regardless of the eagerness of the evaluation, is usually a bad practice. So that's not an argument in favor of bitwise operators.||
and&&
, with this style it's undetermined which ofFoo()
andBar()
will be evaluated first. See also stackoverflow.com/questions/3962068/…&&
on bools and non short-circuiting&
on integers.