Bitwise Operators

Is & or && Bitwise?

Only the single & is bitwise. It compares integers bit by bit, while && is logical AND and checks true or false. Examples in C++ show the difference.

On this page
  1. The short answer
  2. What bitwise AND does
  3. What logical AND does
  4. A side-by-side example
  5. A common mix-up
  6. Short-circuiting
  7. Other uses of the ampersand
  8. Quick rule

The short answer

The single & is bitwise. The double && is not. The single & compares two integers bit by bit. The double && is logical AND: it treats each operand as true or false and returns a bool.

What bitwise AND does

& gives a 1 in a bit position only when both bits are 1:

  0110   (6)
& 0011   (3)
------
  0010   (2)

So 6 & 3 is 2.

What logical AND does

&& converts each operand to bool. Zero counts as false, and any nonzero value counts as true. The result is always true or false.

Because 6 and 3 are both nonzero, 6 && 3 is true. Printed with std::cout, a bool shows as 1 unless you use std::boolalpha.

A side-by-side example

#include <iostream>

int main() {
    int a = 4;  // binary 100
    int b = 2;  // binary 010

    std::cout << "a & b  = " << (a & b) << '\n';   // 0
    std::cout << "a && b = " << (a && b) << '\n';  // 1
    return 0;
}

Output:

a & b  = 0
a && b = 1

The numbers 4 and 2 share no 1 bits, so bitwise AND gives 0. Both are nonzero, so logical AND is true.

A common mix-up

Writing & where you meant && still compiles, so the mistake can go unnoticed. In if (a & b), the test passes only when a and b share a 1 bit. In if (a && b), it passes when both are nonzero. For 4 and 2, the first test fails and the second passes.

Short-circuiting

&& stops as soon as the left side is false, so the right side is never evaluated. & always evaluates both sides. That makes && the safe choice for checks like this:

if (ptr != nullptr && ptr->value > 0) {
    std::cout << "Positive value: " << ptr->value << '\n';
}

With &, both sides run, so ptr->value would be read even when ptr is null. Reading through a null pointer is undefined behavior.

Other uses of the ampersand

A single & in front of a variable, as in &x, is the address-of operator. That is a separate meaning and has nothing to do with bits.

Quick rule

Use & and | when you are working on the bits of an integer. Use && and || when you are combining conditions that are true or false.

The complete guide to bitwise operators

Bitwise XOR in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Unary Operators in C++

Learn what unary operators in C++ are, from the one-operand symbols like !, ~, ++ and * to prefix vs postfix, precedence and common mistakes, with examples.