For the uninitiated, Brainfuck is a Turing-complete language with only 8 commands, all of which have literal equivalents in C:
bf c
----------------------
> ++ptr;
< --ptr;
+ ++*ptr;
- --*ptr;
. putchar(*ptr);
, *ptr=getchar();
[ while (*ptr) {
] }
On any linux distro that has a package manager, you ought to be able to find and install the package beef
, a Brainfuck interpreter so you can play along at home.
As you can see above, Brainfuck has but one control structure, […]
which translates to C as:
while (*ptr) { … }
Which gives you all the control of IF VAR = 0 THEN GOTO 10
from BASIC. The following will call getchar()
until it returns 0
:
, # *ptr = getchar();
[ # while (*ptr) {
>, # *(++ptr) = getchar();
] # }
But what if I only want to read to a newline char \n
? After having some difficulty wrapping my brain around how this could be adapted to work as a simple if
I came up with the following:
, # *ptr = getchar(); /* store input */
---------- # *ptr -= 10; /* test for \n by subtracting 10 before loop */
[ # while (*ptr) { /* if *ptr == 0, last char read was \n */
++++++++++ # *ptr += 10; /* wasn't \n, add 10 back to val under ptr */
>, # *(++ptr) = getchar();
---------- # *ptr -= 10;
] # }
(If anyone has a better way of doing this, please let me know)
Now lets say I want to test break out of that loop on \r
in addition to \n
. How can I test for either, given that I only have one opportunity to break out of the loop? My goal is to be able to emulate switch
, nested if
s or if/else if
s.
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
– Grunberg