Question

I know that interpreting C++ code might not hold practical value and this question is just for entertainment and learning purpose.

Is it possible to interpret C++ code statement by statement instead of compiling it? Please also explain the reason for the answer.

If it is not possible, is there a subset of the language that can be interpreted?

Was it helpful?

Solution

It depends on what you mean with "statement by statement." Most of the time, C++ is a strictly top-to-bottom language: if you want to use anything, you must have declared or defined it previously. So no problem here.

There are exceptions to the top-to-bottom approach, however. For example, the body of a class member function sees declarations of class data members which lexically follow it in source code. It is possible to call an inline function which has been declared, but not yet defined in the translation unit (the definition must appear before the TU ends, though).

These may or may not violate your notion of "statement by statement," depending on what exactly that notion is.

EDIT based on your comment:

If the interpreter has no outlook past the current statement, then it cannot possibly hope to interpret C++ code. Counterexamples using problem points given above:

#include <iostream>

struct C
{
  void foo() { std::cout << i << '\n'; }
  int i;
};

int main()
{
  C c;
  c.i = 0;
  c.foo();
}

Or

#include <iostream>

inline void foo();

int main()
{
  foo();
}

inline void foo()
{
  std::cout << "x\n";
}

It doesn't even have to involve inline functions:

extern int i;

int main()
{
  return i;
}

int i = 0;

OTHER TIPS

There's no clear-cut boundary between compilation and interpretation. Most languages that are usually thought of as interpreted are actually compiled for some kind of VM. The same can be done for C++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top