BrainF**k interpreter in C++
Bug

The only issue I see is that the data array is never expanded.

As a result any value of ptr that is not zero will cause undefined behavior. What you want to do is give a fixed but reasonable size for the data.

std::size_t const maxDataSize = 10000;

...

   std::vector&lt;int&gt; values;
   values.resize(maxDataSize);


Then make sure when you access the data you mod it to the correct range:

        case '&gt;': ptr = (ptr + 1) % maxDataSize; break;
        case '&lt;': ptr = (ptr - 1) % maxDataSize; break;


Comment

This is not a standard C++ header.

#include &lt;bits/stdc++.h&gt;


What you want is

#include &lt;vector&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;


Comment

The code is non modifiable so the the code parameter should be constant. I would also pass by const reference to prevent a copy or require a move operation to pass the code into the interpretor.



I can see how you would interpret the output as what is printed to the output stream by the interpreter as the result. But is not the whole of memory the actual output?



Two things I would do:


Make . output to the output stream (like , takes from the input stream.
I would give the bf_interpreter() two parameters. The code to execute and the data memory that can be used by the program. The data memory is passed by reference so that any changes can be inspected after the interpreter has finished.
Potentially I would even pass two streams (input/output) as parameters to bf_interpreter(). Though that is a bit more subjective.


Thus my function definition would be this:

 std::string bf_interpreter(std::string const&amp; code,
                            std::vector&lt;int&gt;&amp;  memory,
                            std::istream&amp;      input = std::cin,
                            std::ostream&amp;      output = std::cout
                           );


ReDesign

OK. So given there is a lot more state here than I really want to pass as a function. I would change this a bit and create a "Brain Fuck" class where all the important state is passed to the constructor then you can call interpret on the object.

class BF_Engine
{
         // Add Members here
         void nextStep() {
             // Add interpreter here
         }
    public:
         BF_Engine(std::string const&amp; code,
                   std::vector&lt;int&gt;&amp;  memory,
                   std::istream&amp;      input = std::cin,
                   std::ostream&amp;      output = std::cout
                  );

         void interpret(std::size_t steps = 1)
         {
             while (!finished &amp;&amp; steps &gt; 0) {
                 nextStep();
                 --steps;
             }
         }
         void interpretRun()
         {
             while (!finished) {
                 nextStep();
             }
         }
 };