Skip to content

bfpp - embed brainfuck in C++

Okay, I lied; you can't really embed brainfuck in C++ but you can get pretty close. Here is an example:

#include "bfpp.h"

int main() {
  // Prints out factorial numbers in sequence.  Adapted from
  // http://www.hevanet.com/cristofd/brainfuck/factorial.b .
  bfpp
    * + + + + + + + + + + * * * + * + -- * * * + -- - -- & & & & & -- +
    & & & & & ++ * * -- -- - ++ * -- & & + * + * - ++ & -- * + & - ++ &
    -- * + & - -- * + & - -- * + & - -- * + & - -- * + & - -- * + & - --
    * + & - -- * + & - -- * + & - -- * -- - ++ * * * * + * + & & & & & &
    - -- * + & - ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ * -- & + * - ++ + * *
    * * * ++ & & & & & -- & & & & & ++ * * * * * * * -- * * * * * ++ + +
    -- - & & & & & ++ * * * * * * - ++ + * * * * * ++ & -- * + + & - ++
    & & & & -- & -- * + & - ++ & & & & ++ * * -- - * -- - ++ + + + + + +
    -- & + + + + + + + + * - ++ * * * * ++ & & & & & -- & -- * + * + & &
    - ++ * ! & & & & & ++ * ! * * * * ++ 
  end_bfpp
}

I call this variant "bfpp" as it has some pretty significant differences from brainfuck. First of all, some commands had to be adapted; although + and - remain the same,

  • < and > were changed to & and *,
  • . and , were changed to ! and ~ (mnemonic: ! contains . within it and ~ is kind of like a sideways ,),
  • and [ and ] were changed to -- and ++ (mnemonic: [ and ] are the most complex brainfuck commands [to implement, at least] and so deserve to be mapped to the wider and more prominent operators).

This magic is made possible by the fact that brainfuck has exactly eight commands and C++ has exactly eight overloadable symbolic unary operators. Add some macros to hide the C++ scaffolding behind some delimiters and you have a convincing illusion of an embedded language.

bfpp.h implements a simple (<100 lines) bfpp interpreter and the magic described above, and bf2bfpp.c is a straightforward translator from brainfuck to bfpp. Gotta love C++!

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*