Iterationnal Statements

Executes a statement repeatedly, until the value of condition becomes false.

While

Execute a statement until the condition becomes False. All the variables declared in the while block are only visible in the loop expression/body.

If the statement is always True, the loop will run infinitely.

Synopsis

(while (<condition>) {
    <expression-true>
})

The condition must be a boolean variable or expression, the expression will be run while the condition is True.

Example:

(func (doc (int c))
{
    (while (c <= 42) {
        (c = (c + 1));
    })
    (c);
})
(test 2)

We are incrementing the variable c while it is lower or equal than 42. If the variable is higher than 42, the condition will not be true and the block will not be ran.

(func (doc (int c))
{
    (while (c <= 42) {
        (c = (c + 1));
        (int v = c);
    })
    (v);
})
(test 2)

The previous example do not work because we declare a variable v in the while block and we are using it out of it scope.

For

The for is very similar to the while statement but we can have an initialization statement and an iteration statement in addition to the condition that the while have.

The initialization that occurred in the for must stay in the for's scope, otherwise the code will not compile due to an error.

Synopsis

(for (<init-statement>) (<condition>) (<iteration-statement>) {
    <statement-true>
})

if we would change this code to use a while statement, it will look like this:

<init-statement>
(while (<condition>) {
    <statement-true>
    <iteration-expression>
})

We can see that both statement are pretty similar but the for can let you do more things because it have more options.

Example:

(func (doc (int c))
{
    (for (int i = 0) (i < 42) (i = (i + 1)) {
        (c = (c + 1));
    })
    (c);
})
(test 2)

We are incrementing the variable c while a variable i declared in a for is lower than 42.

Last updated