Control Flow
Logic is no longer sequential!
Control flow statements allow for our smart contracts to execute certain logic repeatedly or to execute only a certain block of logic.
If/Else If/Else Statements
The general structure for if/else if/else structures is as follows:
where E
is a boolean expression.
While Loops
The general structure for while
loops is as follows:
where E
is a boolean expression.
Do While Loops
In contrast to while loops, do-while loops executes the logic contained within the loop body first before checking if the loop condition holds. As an example, consider the following psueodocode:
After x
is initialized to 0
, we run one iteration of the do-while block and then check afterwards whether x < 0
. Although the loop condition was never satisfied in the first place, we still end with x = 1
.
In Solidity, do-while loops are as follows:
For Loops
Finally, we will cover for loops. The syntax for loop variables is as follows:
where A
is the loop variable, B
is the loop condition, and C
is the loop updater. An example of a for-loop in Solidity is as follows:
Using uint
As The Loop Variable Type
uint
As The Loop Variable TypeAlthough not required, using uint
as the loop variable type brings the advantage of being able to index arrays without having to do any sort of explicit type conversions.
Aside: break
and continue
break
and continue
At times, we may not want for our loops to continue executing until termination. For this, Solidity provides us with the following keywords:
break
: exit out of the loop completelycontinue
: move onto the next iteration
Examples of these keywords are as follows:
where E
, E'
are arbitrary boolean expressions.
Last updated