Skip to content

Instantly share code, notes, and snippets.

@ikkentim
Last active August 29, 2015 14:14
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 ikkentim/da2fc436a88a18dc79cf to your computer and use it in GitHub Desktop.
Save ikkentim/da2fc436a88a18dc79cf to your computer and use it in GitHub Desktop.
Basic brainfuck interpreter
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream codeFile ("main.bf");
codeFile.seekg(0,ifstream::end);
int size=codeFile.tellg();
codeFile.seekg(0);
char instructions[size];
char memory[30000] = {'\0'};
char input[128] = {'\0'};
codeFile.read(instructions, size);
char *p = memory;
char *i = instructions;
char *c = input;
bool isLoop = false;
cout << "Start main.bf" << endl;
while(*i) {
bool enteredLoop = false;
switch(*i) {
case '>':
p++;
break;
case '<':
p--;
break;
case '+':
(*p)++;
break;
case '-':
(*p)--;
break;
case '.':
cout << *p;
break;
case ',':
while(!*c) {
cin >> input;
c = input;
}
*p = *c;
c++;
break;
case '[':
if(!*p) {
int find = 1;
do {
i++;
switch(*i) {
case '[':
find++;
break;
case ']':
find--;
break;
}
} while(find != 0);
}
else {
enteredLoop = true;
break;
}
break;
case ']':
if(*p) {
if(isLoop) {
cout << "INFINITE LOOP DETECTED" << endl;
return 0;
}
int find = 0;
do {
switch (*i) {
case ']':
find++;
break;
case '[':
find--;
break;
}
i--;
} while (find);
}
break;
}
isLoop = enteredLoop;
i++;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment