There are two Boolean "OR" operators: "|" and "||". First one checks up both left and right Boolean operands in all cases, the second one "||" optimizes the check: if first operand is
true
, there is no need to check up the second operand.
Why not using "||" all the time? Well, this is what I do. But "|" can be needed in case the second Boolean operand is a function with the side effect. If the call is optimized out using "||", the side effect will disappear. The operator "|" will not allow it.
Example:
bool Right() {
bool result =
System.Console.WriteLine("Right returned {0}", result);
return result;
}
bool left = true;
if (left || Right())
if (left | Right())
A very typical Boolean expression for the operand is arithmetic comparison expression:
double a, start, end;
if (a < start || a > end)
System.Console.WriteLine("The value {0} is outside the segment [{1} .. {2}]", a, start, end);
Same thing with Boolean "&&" and "&" operators. The operator "&&" will skip checking of the right operand if the left operand is
false
.
Don't mix up Boolean "|" and binary (set) operator "|"; don't mix up Boolean "&" and binary (set) operator "&".
—SA