/ Esoteric

Brainfuck tutorial part 1

Before we start, you should already know the basics of all the instructions and how the tape works. If you don't already code and don't have pain killers for the headache you will get, turn away now.


One of the most common structures you will see in brainfuck code is a while loop that decrements one each iteration. For example, if cell starts at 20 then the contents of the loop are executed 20 times and after the last iteration cell is 0.


Here we have the loop above but add 3 to the cell to the right. The slide includes the equivalent c code. The code [>+++<-] effectively multiplies the first cell by 3, stores it in the second cell, and the first cell is 0.


A common problem is having to re-code the same operations but with different variable locations on the tape, to make this easier we create templates with named variables.

Templates use letters to indicate where the current pointer is on the tape, when compiling templates you use < and > to move the pointer to the variable

For example we want to compile x[y+x-] and the layout of our tape is x, y where x is tape[0] and y is tape[1]: Since we always start at tape[0] the first x is redundant and does not compile into anything. The second letter in the template is y, since we are at tape[0] and want to go to tape[1] we add a >. The third letter is x again, since the current pointer is y we add a <. This compiles to [>+<-]

Below that is a more complex example, you can use the same steps to turn x[y+z+x-]z[x+z-] with tape x, y, z into [>+>+<<-]>>[<<+>>-].

In this post ill be using templates to make code easier to read as you dont have to worry about tracking the pointer position as you read.


The most common template you use simply moves one cell to another and destroys the original cell. Here we show the template being used with different stack configurations and the equivalent C code.

Brainfuck tutorial part 1
Share this