Boolean Variables

by Martin D. Maas, Ph.D

Logical Operators

Boolean variables true and false are quintessential to computer programming. Let’s describe the basic boolean operations implemented in Julia:

not!xreturns the opposite of x
andx && yreturns true if both operands are true

Importantly, && and || are short-circuited (see Wiki).

This has a series of advantages. In particular, we can do

if a > 0 && expensive_computation(b) > 0

In this way, we avoid performing the expensive computation if it’s not necessary (when a>0 returns false).

Also, you won’t get a nasty error when doing something like

if @isdefined(ge) && ge>0
    print("ge exists and is greater than 0")

because trying to assess whether an undefined variable is greater than zero is usually not permitted in any programming language. If the variable is not defined, the second condition won’t be checked.

As for the or operator, the fact that it is short-circuited means that it will return true if the first expression is true without the need to evaluate the second expression. This can also lead to performance gains.

if 3 > 2 || expensive_computation(b) > 0

The expensive_computation function won’t be called, as the first expression returnes true.

Logical to Number

In Julia, Bool is a subtype of Integer. true equals 1, while false equals zero. In particular, we can do numerical operations on Bool types without the need of any type conversion.

true + true         # 2