brainfark

I wrote my own little brainfuck interpreter. You can read all about brainfuck on the esoteric programming website. They have a whole list of weird programming languages. So what is brainfuck? They tell you all about it on the Esolang website. But I’m gonna tell you anyway.

Brainfuck is a programming language designed to be as small as possible. This does not mean that programs written in brainfuck are neccesarily small. No, it means that the interpreter/compiler can be written in a small number of bytes.

There are only 8 commands in the language:

  • > move pointer right
  • < move pointer left
  • + increase value at pointer
  • - decrease value at pointer
  • . output character at pointer
  • , input character at pointer
  • [ jump past ] if value at pointer is 0
  • ] jump to [ if value at pointer is not 0.

This language is Turing complete, which means that any program may be written in it. This is not recommended however.

I implemented my interpreter in the C programming language, because of its native pointer support. Let’s look at the code:

void eval(char *s, char *p) {
  int i;

  for (; *s; s++)
         if (*s == '>') ++p;
    else if (*s == '<') --p;
    else if (*s == '+') ++*p;
    else if (*s == '-') --*p;
    else if (*s == '.') printf("%c", *p);
    else if (*s == ',') scanf("%c", p);
    else if (*s == '[' && !*p) {
      for (i = 1, s++; i; s++)
        i += (*s == '[') - (*s == ']');
      s--;
    }
    else if (*s == ']' && *p)
      for (i = 1, s--; i; s--)
        i += (*s == ']') - (*s == '[');
}

Doesn’t that look nice and neat? I was very pleased with myself. Until I found out that a lot of people have written brainfuck interpreters in brainfuck itself, that are shorter and of course more elegant. The *s pointer points to the program text. The *p pointer points to the actual data array.

The structure of the program should be familiar if you have ever written any semantic sucking code. We try to match one of the 8 commands and execute logic accordingly. The s-- at the end of the ] is there to ensure the string pointer does not go to far past the matching ].

To actually make this code do something, some additional I/O code needs to be written. Try making an interpreter for yourself and see what happens!

Leave a comment

Your e-mail address will not be published. Required fields are marked *