Cairo’s Function Exercise II

Use the information given in the last section, in order to write a piece of code that when executed puts the current values of ap, fp and pc in memory (say, write ap into [ap], fp into [ap + 1] and pc into [ap + 2]).

Solution

A very simple program useful just to prove a point.

func main():
    [ap] = ap; ap++
    [ap] = fp; ap++
    [ap] = pc; ap++
    ret
end

Trying to execute the program we get the following error:

$ cairo-compile exercise.cairo --output exercise.json
>>>
exercise.cairo:4:12: Unknown identifier 'pc'.
    [ap] = pc; ap++
           ^^

The pc keyword is not recognized by the compiler. Let’s remove that line and compile again.

func main():
    [ap] = ap; ap++
    [ap] = fp; ap++
    ret
end
$ cairo-compile exercise.cairo --output exercise.json
>>>
exercise.cairo:2:12: Invalid RHS expression.
    [ap] = ap; ap++
           ^^
Preprocessed instruction:
[ap] = ap; ap++

Another error, we can’t access the ap pointer directly. Let’s remove that line from the code and just try to access the fp pointer instead.

func main():
    [ap] = fp; ap++
    ret
end
$ cairo-compile exercise.cairo --output exercise.json
>>>
exercise.cairo:2:12: Invalid RHS expression.
    [ap] = fp; ap++
           ^^
Preprocessed instruction:
[ap] = fp; ap++

Failure again. This exercise just helps to prove that we can’t directly access any of the underlying pointers and that we need to use a library instead.

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.