Why && Instead of &?

Why do we use && instead of &? I initially used & in my code, and it worked just fine.

& is bitwise and
&& is logical and

1 Like

Just in addition, the bitwise & will evaluate both sides of the comparison where as the logical && will stop once it’s evaluated as false. The && saves compute cycles and prevents null references that you’ll learn about in later sections.

int x = 4;
int y = 6;
if (x > 5 && y > 5) {
  // code
}

Since x is not greater than 5, the computer will not evaluate whether y is greater than 5 since it doesn’t matter.

1 Like

Thank you! This helped a lot.

1 Like

Also to add to @BillN’s comment. That is known as short-circuiting and also happens with logical or || when the left hand operand is true, it doesn’t evaluate the right hand since it already knows the result is true.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms