Convert string to code at runtime C ++

I generate If Else Expressions in the following format

If(X > 10) Then Fly = True Else Fly = False If(X > 9) Then Fly = True Else Fly = False If(X > 8) Then Fly = True Else Fly = False If(X > 7) Then Fly = True Else Fly = False If(X > 6) Then Fly = True Else Fly = False 

I was wondering. Can I execute these expressions at runtime? I do not know if my question is clear.

I will add an example

 String = ""; for(int i = 0; i < n; i++) { string ="if(x > 10){Fly = true;} else {Fly = False;}"; Execute (Expression HERE)! } 

Is it possible to do this? lol thanks. Hani.

+4
source share
4 answers

You can use TCC ( http://bellard.org/tcc/ ). It allows you to compile and run code initially at run time. Another approach is to use an interpreter, there are many (LUA, Python, etc., see the wiki list).

+4
source

One doesn't just interpret C / C ++ code ... AFAIK you just can't.
(except that you compile another binary and run it from the cmd line, maybe ...)

Note. You can write

 fly = (x > 10); 

instead

 if(x > 10){ fly = true; }else{ fly = false; } 
+4
source

Not. C ++ is a compiled language and has no eval function or the like. You can include a script engine in your program, for example Lua

+3
source

Not unless you apply the Greenspun 10th rule .

+3
source

Source: https://habr.com/ru/post/1501859/


All Articles