Cairo’s Labeled Jump Exercise I

What does the following code do? (run with –no_end –step=16 to avoid the End of program was not reached error)

func main():
    [ap] = 2; ap++

    my_loop:
    [ap] = [ap - 1] * [ap - 1]; ap++
    [ap] = [ap - 1] + 1; ap++
    jmp my_loop
end

Solution

The code clearly creates an infinity loop and that’s why we need to run it using the flag –step=16 to limit the number of iterations. 

After compiling and running the program we get the output shown below:

$ cairo-compile exercise.cairo --output exercise.json
$ cairo-run --program=exercise.json \
--print_memory --relocate_prints --no_end --steps=16
>>>
Addr  Value
-----------
⋮
1     5189976364521848832
2     2
3     5210805504208502784
4     5198420613823168512
5     1
6     74168662805676031
7     -3
8     21
9     21
10    2
11    4
12    5
13    25
14    26
15    676
16    677
17    458329
18    458330
19    210066388900
20    210066388901

The execution of the code makes the pc counter loop while keeping the ap counter moving forward. This creates a progression that doubles the previous value, adds one, doubles it again, adds one, etc. The loop has no end and thus the function doesn’t even need a return statement (it wouldn’t even reach it).

Reference

The exercise in this article can be found in this section of the Cairo docs.

So, what do you think?

This site uses Akismet to reduce spam. Learn how your comment data is processed.