Boolean logic

In the previous section, we can combined gates to solve larger problems with yes/no questions.

Logic in software

When programming, we will often have to deal with decisions on a logical level. To allow us to do that, all programming languages offer some kind of boolean logic operators.

Recap: Boolean values

For this chapter, we will use true and false to refer to our boolean values.

The operators

Let’s see what those operators are:

  • Not (negation)
  • And (conjunction)
  • Or (disjunction)
  • Exclusive Or (XOR)

Let’s dive into each of them!

NOT

This operator is most useful in combination with one of the other two operators or alone. It inverts, i.e. “turns around” a boolean value:

x NOT x
true false
false true

In most programming languages this operator is either expressed as ! (e.g. !x is the negation of a boolean x) or the word not.

A logical circuit for the NOT operator

Example

AND

The logical and operator outputs true when the two input booleans are both true.

x y x AND y
false false false
true false false
false true false
true true true

A logical circuit for the AND operator

Example

In most programming languages this operator is either expressed as && (e.g. x && y) or the word and.

OR

The logical or operator outputs true when at least one of two input booleans is true.

x y x OR y
false false false
true false true
false true true
true true true

A logical circuit for the OR operator

In most programming languages this operator is either expressed as || (e.g. x || y) or the word or.

Example

XOR

The OR operator returns true when at least one of its inputs is true. What if we want to return true when exactly one input is true?

This is a common logical operator called eXclusive OR or XOR for short. It is usually not considered a basic boolean operator. It is a combination of NOT, AND and OR.

Creating the XOR from other operators