Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could C++ also be interpreted instead of compiled?

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?

like image 417
danijar Avatar asked Sep 06 '13 11:09

danijar


Video Answer


1 Answers

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;
like image 165
Angew is no longer proud of SO Avatar answered Sep 30 '22 11:09

Angew is no longer proud of SO