Skip to content

Instantly share code, notes, and snippets.

@tiqwab
Created March 27, 2019 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiqwab/1f454e36b223ffe730eeac46464e2338 to your computer and use it in GitHub Desktop.
Save tiqwab/1f454e36b223ffe730eeac46464e2338 to your computer and use it in GitHub Desktop.
Brainf**k
#include <stdio.h>
#include <stdlib.h>
static char buf[30000];
static char input[30000];
static int idx = 0;
static char *ptr = buf;
void interpreter(int start);
/**
* Brainf**k interpreter implemented in C.
* ref. https://ja.wikipedia.org/wiki/Brainfuck
*/
int main(void)
{
char c;
int i = 0;
for (i = 0;; i++) {
c = getchar();
input[i] = c;
if (c == EOF) {
break;
}
}
interpreter(-1);
return 0;
}
void interpreter(int start)
{
char c;
idx++;
for (;;) {
// printf("%d", idx);
c = input[idx];
if (c == EOF) {
break;
}
// printf("%c\n", c);
if (c == '>') {
ptr++;
} else if (c == '<') {
ptr--;
} else if (c == '+') {
(*ptr)++;
} else if (c == '-') {
(*ptr)--;
} else if (c == '.') {
putchar(*ptr);
} else if (c == ',') {
*ptr = getchar();
} else if (c == '[') {
if (*ptr) {
interpreter(idx-1);
} else {
for (;;) {
c = input[idx];
// printf("%c\n", c);
if (c == ']') {
break;
}
idx++;
}
}
} else if (c == ']') {
idx = start;
return;
} else {
; // skip
}
idx++;
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment