The &
is the and bit operator, so it compares each bit of the checked data and results in 1 whenever the corresponding bit in the two operands is 1, after all the and is only true when both are true, otherwise the result will be 0, so it handles bits.
This is the primary function of it and knowing how to use it well you can do some optimizations (not that you need to) always avoiding unnecessary branches which is a very expensive processor operation. Operations with it can be seen in How to connect a bit to a number? .
Of course, if you do this in a boolean data, only 1 bit is relevant, and they will be calculated and the result can be used as a boolean, then it serves in if
, for example.
It should be understood that if
only accepts a Boolean. Then it can only apply in operands that are 00000000 or 00000001 and is of boolean type. Only the last bit is relevant, without considering endianess .
In a more complex Boolean expression with more than one subexpression this operator will always execute all subexpressions (the operands of &
), no matter the result, in some cases it is what you want, in others you do not have to worry about second subexpression when the result of the first is 0 (false), then you can use &&
.
The &&
is the logical and and does not work with bits, only with the boolean result. It has short circuit , so it only performs the second subexpression if the first one is true.
The same goes for |
and ||
, except that in this case it is a or , then in ||
if the first one is true it does not execute the second because just a subexpression is true for everything to be considered true.
using static System.Console;
public class Program {
public static void Main() {
var x = 1;
var y = 2;
var a = x & y;
var b = x == 1;
var c = y == 2;
var d = x & y;
var e = (x & y) == 0;
WriteLine(a);
WriteLine(d); //note que é um inteiro
WriteLine(e);
//if (x & y) WriteLine("ok"); //não funciona porque if espera um bool e o resultado é int
if (b & c) WriteLine("ok"); else WriteLine(" não ok");
if (Teste(x) & Teste(y)) WriteLine("& - ok"); else WriteLine("&");
if (Teste(x) && Teste(y)) WriteLine("&& - ok"); else WriteLine("&&");
if (Teste(x) | Teste(y)) WriteLine("| - ok"); else WriteLine("|");
if (Teste(x) || Teste(y)) WriteLine("|| - ok"); else WriteLine("||");
if (Teste(y) & Teste(x)) WriteLine("& - ok"); else WriteLine("&");
if (Teste(y) && Teste(x)) WriteLine("&& - ok"); else WriteLine("&&");
if (Teste(y) | Teste(x)) WriteLine("| - ok"); else WriteLine("|");
if (Teste(y) || Teste(x)) WriteLine("|| - ok"); else WriteLine("||");
}
public static bool Teste(int x) {
WriteLine($"Executou {x}");
return x == 2;
}
}
See running on .NET Fiddle . And No Coding Ground . Also I put it in GitHub for future reference .
You can find out more at What are operators for | & < < > >? .
The truth table determines the results of Boolean algebra.