The &
is the bit operator and, then it compares each bit of the verified 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, and so bit manipulation.
This is his primary function and knowing how to use it well can make some optimizations (not that always need) avoiding that exist branches unnecessary that it is a very costly processor operation. Operations with it can be seen in How to connect a bit to a number?.
Of course, if you do this on a boolean die, only 1 bit is relevant, and they will be calculated and the result can be used as a boolean, so it serves as a boolean if
, for example.
It is necessary to understand that the if
only accepts a boolean. So it can only apply to operands that are worth 00000000 or 00000001 and are of the 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 what the result, in some cases it is what you want, in others you do not need to worry about the second subexpression when the result of the first is 0 (false), so you can use the &&
.
The &&
is the and logical and does not work with bits, only with the boolean result. It has short-circuit, then it only executes the second subexpression if the first one is true.
The same goes for the |
and ||
, only in this case it is a or, then on ||
if the first is true does not execute the second because it is sufficient for a subexpression to be 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;
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
You can see more in What are the operators for | & << >>?.
To truth table determines the Boolean algebra results.
Related: https://answall.com/q/224468/1658
– Oralista de Sistemas