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:

if (E) {
    // Insert logic here
} else if (E) {
    // Insert logic here
} else {
    // Insert logic here
}

where E is a boolean expression.

While Loops

The general structure for while loops is as follows:

while (E) {
    // Insert logic here
}

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:

x <- 0
do
    x <- x + 1
while x < 0

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:

do {
    // Insert logic here
} while (E)

For Loops

Finally, we will cover for loops. The syntax for loop variables is as follows:

for (A; B; C) {
    // Insert logic here
}

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:

uint x = 0;
for (uint i = 0; i < 5; i++) {
    x += 1;
}

Using uint As The Loop Variable Type

Although 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

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 completely

  • continue: move onto the next iteration

Examples of these keywords are as follows:

while (E) {
    if (E') {
        break;
    }
}

for (uint i = 0; i < 5; i++) {
    if (E) {
        continue;
    }
}

where E, E' are arbitrary boolean expressions.

Last updated