Wednesday, August 20, 2008

Boolean AND and OR

Yesterday, at the lab, we went into an argument on the boolean operator precedence. We always talk about precedence in arithmetic operators, but the precedence in boolean operator is hardly a topic of discussion. One of my colleague claimed that logical AND has higher priority than the logical OR; I sided with another saying that they have equal priority. So we ended up writing sample programs (in python) to verify our claims:

if a or b and c:
print "true1"
if a and b or c:
print "true2"

It's embarrassing that we had this doubt at this stage of the academic life (6th year Ph.D.). But the funny thing is that we couldn't test our claims because of how the compiler works. The programing languages don't go into processing the second operant of a OR statement, if the first is "true"; same with a AND statement, if the first operant is "false". I don't want to write the whole story of why this feature makes the tests invalid, but think about it and you will see it.

Ultimately, we ended up looking at the language documentation (which we should've done in the first place!) and found out my other colleague is right - the AND operator do have higher priority than the OR operator.

Nothing new in this story, but I was just surprised to see how couldn't test the priority programmatically.