Created
March 27, 2019 13:12
-
-
Save tiqwab/1f454e36b223ffe730eeac46464e2338 to your computer and use it in GitHub Desktop.
Brainf**k
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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