-
-
Save maxcountryman/1699708 to your computer and use it in GitHub Desktop.
| #include <stdio.h> | |
| #include <string.h> | |
| #include <stdlib.h> | |
| // 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; | |
| void interpret(char* input) { | |
| 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() { | |
| interpret(",[.[-],]"); // outputs input | |
| return 0; | |
| } |
Why not turn the chain of if else if's into a single switch statement. would be much more readable.
@TheSoftwareGuy that's debatable
@nickdesaulniers you are right, the implementation of [ is not correct
else if (current_char == '[' && *ptr == 0) { loop = 1; while (loop > 0) { current_char = input[++i]; if (current_char == '[') { loop++; } else if (current_char == ']') { loop--; } } }
this is a edit to make it actually work with the [
Hi @maxcountryman, just letting you know I used your code for personal work and did a little update of it, here is my gist.
Thanks for this :)
[ should branch
http://www.muppetlabs.com/~breadbox/bf/
Nice!
I'll borrow your code to create my own repository (I didn't figure out how to convert the gist => github repository, I'm still new here). Here is the link.
[ should branch http://www.muppetlabs.com/~breadbox/bf/
Indeed.
Did you use the tests on http://www.brainfuck.org/tests.b ?
Why not turn the chain of if else if's into a single switch statement. would be much more readable.