hp
toc

Interpreting brainfuck in C

2018-09-08, post № 202

brainfuck, C, programming, #interpreter

Esoteric programming languages come in an astonishing magnitude of variety — golfing languages, Turing tarpits, obfuscation languages, one-time joke languages and plenty more. However, among all of them, brainfuck is by far one of the most intriguing to me — an elegant combination of syntactic brevity, apparent lack of functionality and the theorectical might of a Turing machine.
Combined with its seemingly trivially realizable implementation, I have implemented brainfuck in Python 2, a brainfuck flavour in Python 2, and even written an interpreter in DrRacket.
However, like Cristofani writes in their The Epistle to the Implementors, writing a satisfactory brainfuck interpreter is no easy task.
Therefore I have designed another brainfuck command-line interpreter, written in pure C (brainfuck.c).

Key features of this implementation are a large tape size, source code pre-processing — instruction condensing and loop matching —, apt command-line flags and C execution speed.
For further detail on the interpreter’s usage, compile the interpreter (e. g. gcc -O2 brainfuck.c -o brainfuck) and run ./brainfuck -h.

To better demonstrate brainfuck’s true power, I wrote a non-Kolmogorov-complexity program; a palindrome tester.

[ A palindrome tester written in brainfuck. ]
[ Jonathan Frech, 21st of August 2018.      ]
[ Tape layout: (STR ... STR NUL FLG ACC)    ]

,[>,]             read in STR
>+                set FLG to true
<<<[              while STR is of length at least two
 [<]>             go to the first byte
 [[>]>>+<<<[<]>-] transfer first byte to ACC
 >[>]<            go to last byte
 [->>>-<<<]       subtract last byte from ACC
 >>>[             if ACC is not zero
  <[-]            set FLG to false
  >-]             clear ACC
 <[<+>-]          move FLG over
 <<<<             go to last byte
]>>>.             output FLG
% echo ",[>,]>+<<<[[<]>[[>]>>+<<<[<]>-]>[>]<[->>>-<<<]>>>[<[-]>-]<[<+>-]<<<<]>>>.\!existence" > palindrome.b
% ./brainfuck -x palindrome.b
00000000: 00                                       .               

% echo ",[>,]>+<<<[[<]>[[>]>>+<<<[<]>-]>[>]<[->>>-<<<]>>>[<[-]>-]<[<+>-]<<<<]>>>.\!hubbibbuh" > palindrome.b
% ./brainfuck -x palindrome.b
00000000: 01                                       .
Jonathan Frech's blog; built 2024/08/31 22:59:44 CEST