Skip to content

SpecificationIV · Expressions and operators

4.5

Logical operators

And, Or and Not combine boolean answers: And needs both to be true, Or is happy with one and Not turns the answer around.

Markdown version

4.5.1 How it works

The three operators only accept Boolean values and return a Boolean.

aba And ba Or bNot a
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

ProgramCombining conditions

Algorithm Logica
  Define edad As Integer <- 15;
  Define socio As Boolean <- False;
  Write edad >= 12 And edad < 18, " ", Not socio, " ", edad < 12 Or socio;
EndAlgorithm

Output

true true false

The program finishes normally.

4.5.2 Short circuit

And and Or evaluate the left part first. If that is enough to know the answer, the right part is not computed:

  • False And … is always False.
  • True Or … is always True.
Figure 4.5-1.With And, a false left side decides without looking at the right. With Or, a true left side does.

At the top, False And a crossed-out division by zero: the result is False without computing the right side. Below, True Or the same division: the result is True.

ProgramThe right side that is never computed

Algorithm Cortocircuito
  Write True Or 1 Div 0 = 0, " ", False And 1 Div 0 = 0;
EndAlgorithm

Output

true false

The program finishes normally.

The division by zero is there, but it never runs, so it does not stop the program. The short circuit suppresses the effects and failures of the right side; what it does not suppress is type checking: the right side must be a valid Boolean even when it is not computed.

In short

  • And needs both true; Or, at least one; Not inverts.
  • They only accept Boolean.
  • The right side of And and Or is only computed when needed.