Is it possible that a string variable can be parsed as an actual line of code in C++? For example, can this string, "x=0"
, be parsed as actual code and set the value of x
(some random variable in the program) to zero? What I plan to do with this is that I want to make a simple plotter in C++. The user enters the function (The function will be in terms of x
and y
and will have the value zero) to plot as a string (like 2*y+x
), which then will be converted to a code object and then evaluated accordingly using a loop.
Parsing string as a line of code in C++
1.2k Views Asked by AudioBubble AtThere are 3 best solutions below

Because C++ is a compiled and linked language it is not suitable for on-the-fly evaluation.
But I've achieved something similar to your aims in the past with C++ by embedding a Python interpretter to evaluate Python code as strings on the fly and pass the results to the C++ code.
Some other popular scripting languages that can be embedded in a C++ program are Lua and Squirrel.
In Java I've done the same by embedding a Groovy interpretter.
You need to integrate the scripting language interpretter into your code by "embedding" it and then pass values from the scripting language code to your C++ code by a process of "marshaling"
If you really want C++ syntax that can be interpretted, it is theoretically possible to develop a dynamic parser and interpretter for a subset of the language, but C++ is a complex language and such a task would be an enormous undertaking fraught with difficulty and essentially a case of using the wrong tool for the job.

The short answer is "Yes". Compiling C++ on the fly works just fine using a C++ JIT. From llvm.org
A Just-In-Time (JIT) code generation system, which currently supports X86, X86-64, ARM, AArch64, Mips, SystemZ, PowerPC, and PowerPC-64.
The assumption is that you're willing to link most of a compiler into your program in order to achieve this. With concerted effort you should be able to write "eval" on top of the existing API.
The short answer is "No". You can't compile C/C++ "on the fly" like that, as it's a compiled language, not an interpreted one.
But here's an idea: you could embed a JavaScript interpreter, using the SpiderMonkey API, which can interpret all your example code snippets, as JavaScript syntax is very similar to C/C++ in this regard.