Execute Brain****/C: Difference between revisions

adding another example since the existing one doesn't support nested loops, probably a bug
No edit summary
(adding another example since the existing one doesn't support nested loops, probably a bug)
Line 1:
Simple BF engine with infinite tape support.
<lang c>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void bf_run(char *s) {
int len = 1, d = 0;
char *tape = calloc(len, 1);
 
int run(int skip) {
for (; d >= 0 && *s; s++) {
if (d >= len) {
tape = realloc(tape, len * 2);
memset(tape + len, 0, len);
len = len * 2;
}
 
if (*s == ']') return tape[d];
if (*s == '[') {
char *p = ++s;
while (run(!tape[d])) s = p;
continue;
}
 
if (skip) continue;
 
#define CASE(a, b) if (*s == a) { b; continue; }
CASE('+', tape[d]++);
CASE('-', tape[d]--);
CASE('>', d++);
CASE('<', d--);
CASE('.', putchar(tape[d]));
CASE(',', tape[d] = getchar());
}
return 0;
}
 
run(0);
free(tape);
}
 
int main(void) {
bf_run( "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++.."
"+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");
 
return 0;
}</lang>
 
This is a simple function that will run Brain**** code.
The code can be fed from a file or anything else. Here it's entered directly (it reverses a string you type).
Anonymous user