Skip to content

Instantly share code, notes, and snippets.

@vladris
Last active June 12, 2019 10:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladris/feaaa35acc8c74e6eda30b8493e752a3 to your computer and use it in GitHub Desktop.
Save vladris/feaaa35acc8c74e6eda30b8493e752a3 to your computer and use it in GitHub Desktop.
Tiny Brainfuck interpreter
#include <array>
#include <fstream>
#include <iostream>
using namespace std;
const size_t memory_size = 1024;
template <typename It>
It& skip(It&& it, char from, char to) {
while (*++it != to) if (*it == from) skip(it, from, to);
return it;
}
int main(int argc, char *argv[]) {
ifstream fs(argv[1]);
string program((istreambuf_iterator<char>(fs)), istreambuf_iterator<char>());
auto ip = program.begin();
array<char, memory_size> memory{ };
auto data = memory.begin();
while (ip != program.end()) {
switch (*ip++) {
case '>': data++; break;
case '<': data--; break;
case '+': (*data)++; break;
case '-': (*data)--; break;
case '.': cout << *data; break;
case ',': cin >> *data; break;
case '[': if (!*data) skip(ip, '[', ']'); break;
case ']': if (*data) ip = skip(reverse_iterator<string::iterator>(ip), ']', '[').base(); break;
}
}
}
@vladris
Copy link
Author

vladris commented Aug 20, 2018

Pass brainfuck source file as argument to the program: bf <file>.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment