0

I was wondering if there was a way to run code stored as a string in a variable. Ie str code = "i=5+6" Anyone got any ideas?

  • 1
    What is the problem you are trying to solve? What have you tried? Are you referring to a macro, an alias? be specific – ryyker Feb 08 '21 at 00:04
  • @ryyker I think he wants c equivalent of ```exec('i = 5 + 6')``` of python. – MarkSouls Feb 08 '21 at 00:15
  • Write an interpreted that understands the syntax (and semantics) of the code in the string, Pass the string to the interpreter and let it evaluate the code. – thurizas Feb 08 '21 at 00:15
  • Nothing built in to C, no. But a google search for "[c expression evaluator source code](https://www.google.com/search?q=c+expression+evaluator+source+code)" will find lots of expression evaluators out there. – Steve Summit Feb 08 '21 at 00:20

1 Answers1

3

The C language itself has no evaluation function as you find in many interpreted languages.

For an interpreted language, where the source code is passed to an interpreter for execution, it is very easy to later on pass a string to the same interpreter.

C is typically a compiled language, it is passed to a compiler program that translates the C code into CPU instructions that are directly executed by your CPU. The same thing would need to happen with your string content. Yet the system running a compiled C program may not even have a compiler installed as a compiler is not required to run the final program, only to create it.

To dynamically run C code, your program would need to have an entire compiler built-in or a C interpreter.

See also:

Is there an interpreter for C?

https://www.drdobbs.com/cpp/building-your-own-c-interpreter/184408184

This is nothing for a beginner, though, this is something most C experts would not even consider.

If you dynamically need to execute code at runtime, the easiest I can think of is using Lua. The Lua interpreter can be linked into your program, it's very small for a language interpreter, and you can then pass a string of Lua code to the interpreter at runtime.

https://www.lua.org/

Of course, there are even smaller interpreters for other languages (e.g. Lisp) but IMHO most programmers would not find those other languages very appealing while Lua will immediately look common to them.

Mecki
  • 125,244
  • 33
  • 244
  • 253