Skip to content

Instantly share code, notes, and snippets.

@kcal2845
Forked from maxcountryman/bf.c
Last active January 7, 2019 06:07
Show Gist options
  • Save kcal2845/42ef397e82d4986d3d67b5c1f0f202fe to your computer and use it in GitHub Desktop.
Save kcal2845/42ef397e82d4986d3d67b5c1f0f202fe to your computer and use it in GitHub Desktop.
A simple brainfuck interpreter in C
#include <stdio.h>
#include <string.h>
void interpret(char input[]) {
// initialize the tape with 30,000 zeroes
unsigned char tape[30000] = {0};
// set the pointer to point at the left-most cell of the tape
unsigned char* ptr = tape;
char current_char;
size_t i;
size_t loop;
for (i = 0; input[i] != 0; i++) {
current_char = input[i];
if (current_char == '>') {
++ptr;
} else if (current_char == '<') {
--ptr;
} else if (current_char == '+') {
++*ptr;
} else if (current_char == '-') {
--*ptr;
} else if (current_char == '.' ) {
putchar(*ptr);
} else if (current_char == ',') {
*ptr = getchar();
} else if (current_char == '[') {
continue;
} else if (current_char == ']' && *ptr) {
loop = 1;
while (loop > 0) {
current_char = input[--i];
if (current_char == '[') {
loop--;
} else if (current_char == ']') {
loop++;
}
}
}
}
}
int main() {
char code[5000];
printf("type your BF code.\n");
scanf("%s",code);
interpret(code);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment