Implementing Brainfuck loops in an interpreter

前端 未结 5 2287
隐瞒了意图╮
隐瞒了意图╮ 2021-02-20 07:53

I want to build a Brainfuck (Damn that name) interpreter in my freshly created programming language to prove it\'s turing-completeness.

Now, everything is clear so far (

5条回答
  •  有刺的猬
    2021-02-20 08:25

    From the top of my head, might be some errors in it, but something like this should work:

    char* interpret(char* instructions){
      char* c = instructions;
      while (*c) {
        if (*c == ".") putchar(*p);
        else if (*c == ",") *p = getchar();
        else if (*c == '+') (*p)++;
        else if (*c == '-') (*p)--;
        else if (*c == '<') p--;
        else if (*c == '>') p++;
        else if (*c == '[') c = interpret(c+1);
        else if (*c == ']') { if (*p) c = instructions else return c; }
        c++;
      }
      return 0;
    }
    

    Call interpret with the brainf*ck source code. The pointer p is to the current memory position. Do a recursive call when spotting a [. Return from this recursive call when encountering a ].

提交回复
热议问题