Convert string to code at run time c++

巧了我就是萌 提交于 2019-12-19 07:52:26

问题


I am generating If Else Expressions of 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 this expressions at run time? I don't know if my question is clear.

I'll 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 even possible to do it? lol Thank you. Hani.


回答1:


It is possible to use TCC ( http://bellard.org/tcc/ ). It allows to compile and run code natively at runtime. Another approach is to use an interpreter, there are plenty out there (LUA, Python etc, see list wiki).




回答2:


One does not simply interpret C/C++ code... AFAIK you just can't.
(except if you compile another binary and run it from cmd line maybe...)

Note: You can write

fly = (x > 10);

instead of

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



回答3:


No. C++ is a compiled language and has no eval-function or the-like. You may want to include a scripting engine into your program, like Lua




回答4:


Not unless you apply Greenspun's 10th rule.



来源:https://stackoverflow.com/questions/18766048/convert-string-to-code-at-run-time-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!