### Logical Operators

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

Operator Syntax Description
not !x returns the opposite of x
and x && y returns true if both operands are true
or x || y returns true if at least one of the operands is 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
do_something()
end


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")
end


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
do_something()
end


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