3.5 Control Flow

Conditions

Conditional statements allow you to execute different blocks of code based on specific conditions.

The following example demonstrates an if statement that checks the value of a variable a and updates it accordingly:

let a: u8 = 1u8;

if (a == 1u8) {
    a += 1u8;
} 
else if (a == 2u8) {
    a += 2u8;
} 
else {
    a += 3u8;
}

In this case:

  • If a is 1, it increments by 1.

  • If a is 2, it increments by 2.

  • Otherwise, it increments by 3.

Assert

Assertion are special instructions that allows to stop the execution of a transition under a specific condition.

They can be used simply as follows:

This code will always fail when condition is false, and run fine when condition is true.

Here is a more useful example:

This transition won't ever be able to be called by none other than aleo1hn9z4zt6awd6ts9zn8ppkwwvjwrg04ax48krd0fgnnzu6ezg9qxst3v26j .

assert are extremely useful, in particular to validate user inputs.

Loops

A for loop is used to iterate over a range of values. The loop runs a specific number of times, making it ideal for iterating over sequences or performing repeated operations.

  • The loop variable is declared with a type.

  • The loop iterates from the lower_bound to the upper_bound - 1.

  • The bounds must be integer constants of the same type.

  • The lower_bound must always be less than the upper_bound.

This example demonstrates a simple for loop that counts from 0 to 4 and keeps track of the count:

  • The loop runs from 0 to 4, iterating 5 times.

  • count is incremented during each iteration.

  • The function returns 5.

While this code is invalid:

Something like this could be used instead:

Last updated