Monday 28 February 2011

The Human and Computer OR

There is often some confusion between normal humans (i.e. not software designers) and computers regarding the use of "or".

The human way:

  • are you going to the movies this evening or tomorrow evening?

To most humans this is an exclusive or indicating that only one of the options is possible.

The computer way:

  • are you going to the movies this evening or tomorrow evening?
To a computer, the answer to a boolean condition is either yes (true/1) or false (false/0).
  • The computer will answer yes if you're going to the movies this evening.
  • The computer will answer yes if you're going to the movies tomorrow evening.
  • The computer will answer yes if you're going to the movies this evening AND tomorrow evening

Short-circuit evaluation

Most computer languages will not evaluate conditions that have no (longer any) influence on the total result.

So, an if statement containing one more AND operators will stop evaluation if one condition evaluates to false, because the total will always be false.

So, an if statement containing one more OR operators will stop evaluation if one condition evaluates to true, because the total will always be true.

If you wish to explicitly evaluate all operators in Java, try the | (OR) and & (AND) operators instead.

Good luck!

No comments:

Post a Comment