The Difference Between & and &&

Much like with the = and == operators, it can be very easy to make the mistake of swapping one of the logical operators for its bitwise counterpart (& and && for example). Logical operators and bitwise operators might sometimes work the same if you are lucky, but they are not the same, and can sometimes yield completely different results.

• & is the bitwise AND operator
• 0b1010 & 0b1101 —> 0b1000
• && is the logical AND operator
• 0b1010 && 0b1101 —> 0b0001 (TRUE)
• <Non-Zero Value> && <Non-Zero Value> —> 1 (TRUE)

Be careful not to confuse & and &&. They are not interchangeable!

For example, if we perform a bitwise and "&" between the nibble 0b1010 and 0b1101, we get a result of 0b1000. Then, if we perform a logical and "&&" between the same two nibbles, we get a different result -> TRUE, which is usually represented by a value of 1 (or 0b0001 in binary).

Now, note that in this situation, both results would evaluate to a non-zero value, so if used in a conditional expression, they would both be interpreted as TRUE. If however, you were interested in the numeric result of a bitwise AND operation, the result of using "&&" would be completely wrong.

### Example 1 – Using A Bitwise AND Operator

In example 1, we use a bitwise AND, which results in a zero value, so the text does NOT print:

0b1010 AND 0b0101 —> 0b0000

This is a common bug for beginners (and sometimes experts). The evaluation of the expression has a completely different result from the desired logical AND.

### Example 2 – Using A Logical AND Operator

In example 2, we use a logical AND, which results in a non-zero value, so the text does print:

0b1010 AND 0b0101 —> 0b0001 (TRUE)

Remember: with a logical AND, if both operands are non-zero, then the result is non-zero or TRUE (usually a value of 1).