Control Flow
Control flow statements are used to control the flow of execution in a program. They are used to make decisions, to repeat a block of code, and to exit a block of code early. Move has the following control flow statements (explained in detail below):
if
andif-else
- making decisions on whether to execute a block of codeloop
andwhile
loops - repeating a block of codebreak
andcontinue
statements - exiting a loop earlyreturn
statement - exiting a function early
Conditional Statements
The if
expression is used to make decisions in a program. It evaluates a
boolean expression and executes a block of code if the expression is
true. Paired with else
, it can execute a different block of code if the expression is false.
The syntax for the if
expression is:
if (<bool_expression>) <expression>;
if (<bool_expression>) <expression> else <expression>;
Just like any other expression, if
requires a semicolon, if there are other expressions following
it. The else
keyword is optional, except for the case when the resulting value is assigned to a
variable. We will cover this below.
Let's see how we can use if
and else
to assign a value to a variable:
Here we assign the value of the if
expression to the variable y
. If x
is greater than 0, y
will be assigned the value 1, otherwise 0. The else
block is necessary, because both branches must
return a value of the same type. If we omit the else
block, the compiler will throw an error.
Conditional expressions are one of the most important control flow statements in Move. They can use
either user provided input or some already stored data to make decisions. In particular, they are
used in the assert!
macro to check if a condition is true, and if not, to
abort execution. We will get to it very soon!
Repeating Statements with Loops
Loops are used to execute a block of code multiple times. Move has two built-in types of loops:
loop
and while
. In many cases they can be used interchangeably, but usually while
is used when
the number of iterations is known in advance, and loop
is used when the number of iterations is
not known in advance or there are multiple exit points.
Loops are helpful when dealing with collections, such as vectors, or when we want to repeat a block of code until a certain condition is met. However, it is important to be careful with loops, as they can lead to infinite loops, which can lead to gas exhaustion and the transaction being aborted.
The while
loop
The while
statement is used to execute a block of code as long as a boolean expression is true.
Just like we've seen with if
, the boolean expression is evaluated before each iteration of the
loop. Just like conditional statements, the while
loop is an expression and requires a semicolon
if there are other expressions following it.
The syntax for the while
loop is:
while (<bool_expression>) { <expressions>; };
Here is an example of a while
loop with a very simple condition: