Question

Will somebody please describe this brainfuck interpreter for me??

    #include <stdlib.h>
    char m[9999], *n[99], *r = m, *p = m + 5000, **s = n, d, c;
    main() 
    {
       for (read(0, r, 4000); c = *r; r++)
              c - ']' || (d > 1 || 
              (r = *p ? *s : (--s, r)), !d || d--), c - '[' || d++ ||
              (*++s = r), d || (*p += c == '+', *p -= c == '-', p += c == '>', 
              p -= c == '<', c - '.' || write(2, p, 1), c - ',' || read(2, p, 1));
    }
Was it helpful?

Solution

The inner loop uses a short circuiting boolean expression (and the comma operator instead of a semicolon) to evaluate each brainfuck token.

Each instance of <expr a> || <expr b> can be translated into if (!<expr a>) { <expr b> }

Each use of the comma operator outside of (r = *p ? *s : (--s, r)) can be replaced with a semicolon.

The list of p <op>= <conditional> and *p+= <conditional> can be replaced with if (<conditional>) p <op>= 1 and if (<conditional>) *p <op>= 1. And that whole parenthesized collection can be transformed into if (!d) { ... }.

Once you've done all that you end up with a pretty simple brainfuck interpreter. Just remember, the comma operator as an expression evaluates left to right.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top