Why does & exist? My book tells me that & will check for both conditions to be false even if the first one is false, but it is pointless checking if the second condition is false anyway because the first will always make the entire thing false if it is false.
Share
&&is the “boolean AND” operator. It evaluates to true if both its operands are true, and false otherwise. It only evaluates the second term if the first is true, because that’s a useful optimization.&is the “binary AND” operator. It evaluates to the result of applying a bitwise AND operation to its operands. The type of this value is the same as the type of the operands, which can be any integral type or bool. It always evaluates both of its operands.For boolean operands, the only real practical difference between
&and&&is that the first always evaluates both operands, while the other performs a short-circuit evaluation.For integral operands, only the
&operator can be used, of course. Example of a bitwise AND on integers:This is because 17 is 10001, bitwise, 13 is 1101. So the operation is:
The same applies to the binary and boolean OR operators (
|and||).The binary & operator can also function as a unary operator, where it returns the address of the variable it is applied to, as in C. This is can only be used in
unsafecode. Example:Hopefully that clears things up a bit.