Skip to content

Instantly share code, notes, and snippets.

@agasiev
Created November 10, 2012 04:09
Show Gist options
  • Save agasiev/4049853 to your computer and use it in GitHub Desktop.
Save agasiev/4049853 to your computer and use it in GitHub Desktop.
Simple brainfuck interpreter
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main(int, char **) {
const size_t memory_buffer_size = 30000;
unsigned char memory[memory_buffer_size];
memset(memory, 0, memory_buffer_size);
short caretPos = 0, inputPos = 0;
std::string input;
std::cin >> input;
while (inputPos < input.length()) {
switch (input[inputPos]) {
case '>':
caretPos++;
break;
case '<':
caretPos--;
break;
case '+':
memory[caretPos]++;
break;
case '-':
memory[caretPos]--;
break;
case '.':
std::cout << memory[caretPos];
break;
case ',':
int temp;
std::cin >> temp;
memory[caretPos] = temp % 256;
break;
case '[':
if (memory[caretPos] == 0) {
int bracketCnt = 1;
inputPos++;
while (bracketCnt && inputPos < input.length()) {
if (input[inputPos] == ']') bracketCnt--;
if (input[inputPos] == '[') bracketCnt++;
inputPos++;
}
assert(bracketCnt == 0);
}
break;
case ']':
if (memory[caretPos] != 0) {
int bracketCnt = 1;
inputPos--;
while (bracketCnt && inputPos < input.length()) {
if (input[inputPos] == ']') bracketCnt++;
if (input[inputPos] == '[') bracketCnt--;
inputPos--;
}
assert(bracketCnt == 0);
}
break;
default:
throw;
}
inputPos++;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment