Java Programming: & vs &&

Status
You're currently viewing only MrMills's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

MrMills

Ars Praefectus
3,727
Moderator
Your prof is a bad programmer.

Short-circuit Boolean evaluation is a GOOD THING. It allows you to optimize your expressions to run in maximum time and also allows you to write expressions like

if((p != NULL) && (p->next != NULL)) doSomething();

Note that in that case, evaluating the second expression would cause an access violation if p was NULL.

The problem with using & as a Boolean operator is that True is usually, but not always, 1. So:

1001 &
0110 =
0000

Whoops! True and true equal false! Not good.

If you seriously want to always evaluate both sides, most compilers offer a "complete Boolean evaluation" option. Or you can assign partial results to two variables and then && those together:

b0 = p == NULL;
b1 = iterations < 21;
if(b0 && b1) ...

Anyway, you should always use short-circuit logic, and even purposely structure it to optimize speed. If you've got a bunch of stuff and'ed together, put the expression that's most likely to be false first. If your expressions are or'ed, then put the one most likely to be true first.
 
Status
You're currently viewing only MrMills's posts. Click here to go back to viewing the entire thread.
Not open for further replies.