Why is &&
preferable to &
and ||
preferable to |
?
I asked someone who\'s been programming for years a
OK, on face value
Boolean a = true;
Boolean b = false;
Console.WriteLine("a({0}) && b({1}) = {2}", a, b, a && b);
Console.WriteLine("a({0}) || b({1}) = {2}", a, b, a || b);
Console.WriteLine("a({0}) == b({1}) = {2}", a, b, a == b);
Console.WriteLine("a({0}) & b({1}) = {2}", a, b, a & b);
Console.WriteLine("a({0}) | b({1}) = {2}", a, b, a | b);
Console.WriteLine("a({0}) = b({1}) = {2}", a, b, a = b);
produce the same answer. However, as you showed, if you have a more complex question so:
if (a and b and c and d) ..
If a
is not true and maybe b
is a function where it has to go off, connect to something, get this, do that, make a decision.. why bother? Waste of time, you know it's already failed. Why make the machine go off and do extra pointless work?
I've always used &&
because I put the most likely to fail first, ergo, less calculations before moving on when there is no point. If there is no way to predict less likely choices, such as you have a boolean to limit output of data, something like:
if (limit && !MyDictionary.ContainsKey("name"))
continue;
If it's not limit
, don't bother checking for the key, which could take longer..
Because &&
and ||
are used for flow control just like if/else
are. It isn’t always about conditionals. It is perfectly reasonable to write as a statement, not as an if
or a while
conditional, the following:
a() && b() && c() && d();
or even
w() || x() || y() || z();
It’s not just that it those are easier to type than the equivalent if/else
versions; they are also much easier to read and understand.
Quickest (and slightly dumbed down) way to explain this to people who do not NEED to know the exact operations of the code when doing this is
&& is doing a check on each of those conditions Until it finds a false and returns the entire outcome as false
|| is doing a check on each of those conditions Until it finds a true and returns the entire outcome as true.
& is doing MATHS based apon BOTH/ALL the conditions and dealing with the outcome.
| is doing MATHS based apon BOTH/ALL the conditions and dealing with the outcome.
I've never come across a point where I have needed to use & or | within an if statement. I mostly use it for cutting up Hexadecimal values into its component colours using bitwise shift.
EG:
r = fullvalue >> 0xFF & 0xFF;
g = fullvalue >> 0xF & 0xFF;
b = fullvalue & 0xFF;
Within this operation "& 0xFF" is forcing to only look at of the binary value. I have not personally found a use for | yet though.
&&
is the short circuit version of &
.
If we are evaluating false & true
, we already know from looking at the first argument that the result will be false. The &&
version of the operator will return a result as soon as it can, rather than evaluate the whole expression. There is also a similar verion of the |
operator, ||
.