Eli Richardson
Eli Richardson

Reputation: 930

Brainfuck interpreter in C++ produces incorrect result

I'm writing a Brainfuck interpreter in C++ and I'm having trouble getting this to work correctly. I'm new to C++, but I know JavaScript, which is why I'm writing this interpreter using my JavaScript code (which works perfectly) for reference.

#include <iostream>
#include <vector>

using namespace std;
void printVec(vector<int> arr) {
  for (int i = 0; i < arr.size(); i ++) {
    cout << arr[i] << ", " << endl;
  }
}
vector<int> brain(string code, string input = "") {
  vector<int> tape(1);
  vector<string> stack(0);
  int cur = 0;
  int mem = 0;
  for (int i = 0; i < code.length(); i ++) {
    switch (code[i]) {
      case '+':
        tape[cur]++;
        tape[cur] %= 256;
        break;
      case '-':
        tape[cur]--;
        if (tape[cur] < 0) tape[cur] = 256 - tape[cur] * -1;
        break;
      case '>':
        cur++;
        try {
          tape.at(cur);
        } catch (out_of_range& oor) {
          tape.push_back(0);
        }
        break;
      case '<':
        cur--;
        if (cur < 0) {
          cout << "Index too low!" << endl;
          throw 1;
        }
      case '[':
        mem = i;
        break;
      case ']':
        if (tape[cur] > 0) i = mem;
        break;
    }
  }
  return tape;
}
int main() {
  printVec(brain("+++[>++<-]"));
  return 0;
}

This produces 0, 2 as the output, when it should be 0, 6. I think the problem is with the way I handle Brainfuck loops (cases '[' and ']') but I can't figure out the exact issue. In JavaScript, the code for these cases looks almost exactly the same, but it works fine.

Any help will be appreciated, including any tips on how to write other parts of this code better.

Upvotes: 2

Views: 328

Answers (1)

vacawama
vacawama

Reputation: 154583

Your case '<': is missing a break and thus will fallthrough and perform the function of case '[' as well. Add the missing break; and see if that is your only issue.

  case '<':
    cur--;
    if (cur < 0) {
      cout << "Index too low!" << endl;
      throw 1;
    }
    break;        // Add this
  case '[':
    mem = i;
    break;

Upvotes: 1

Related Questions