Skip to content

Instantly share code, notes, and snippets.

@akoskovacs
Created November 23, 2015 01:29
Show Gist options
  • Save akoskovacs/ce2b6763182c45bc89ff to your computer and use it in GitHub Desktop.
Save akoskovacs/ce2b6763182c45bc89ff to your computer and use it in GitHub Desktop.
Small Brainfuck interpreter in C++
#include <iostream>
#include <fstream>
#include <cstring>
namespace bfck {
#define BRAINFUCK_ARRAY_SIZE 30000
void interpretFile(const char *);
void eval(int = 0);
char bfa[BRAINFUCK_ARRAY_SIZE];
int bptr;
std::string program;
}
int main(int argc, const char *argv[])
{
argv++;
while (--argc > 0) {
bfck::interpretFile(*argv);
argv++;
}
return 0;
}
using namespace std;
void bfck::interpretFile(const char *filename)
{
ifstream file(filename);
memset(bfck::bfa, 0, BRAINFUCK_ARRAY_SIZE);
string line;
while (getline(file, line)) {
bfck::program += line;
}
file.close();
bfck::eval();
}
void bfck::eval(int from)
{
using bfck::bptr;
using bfck::bfa;
using bfck::program;
bptr = 0;
int pc = from;
char ch;
int l;
while ((ch = program[pc]) != '\0') {
switch (ch) {
case '[':
if (bfa[bptr] == 0) {
l = 1;
while (l > 0 && program[pc] != '\0') {
pc++;
if (program[pc] == '[') {
l++;
} else if (program[pc] == ']') {
l--;
}
}
}
break;
case ']':
l = 1;
while (l > 0 && pc > 0) {
pc--;
if (program[pc] == '[') {
l--;
} else if (program[pc] == ']') {
l++;
}
}
pc--;
break;
case '>':
if (bptr >= BRAINFUCK_ARRAY_SIZE)
bptr = 0;
else
bptr++;
break;
case '<':
if (bptr <= 0)
bptr = BRAINFUCK_ARRAY_SIZE-1;
else
bptr--;
break;
case '+':
bfa[bptr]++;
break;
case '-':
bfa[bptr]--;
break;
case '.':
printf("%c", bfa[bptr]);
break;
case ',':
bfa[bptr] = getc(stdin);
break;
default: break;
}
pc++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment