You are here:

C/How can i evaluate expression in if condition

Advertisement


Question
QUESTION: I want to evaluate string expression in if stmt.
E.g.
int i = 0,j = 2;
char * str = "(i == 0) || (j == 2)";

if(str) /* This should execute code within if condition*/
{
.
}
My condition string is generated at runtime and can be of n level condition(Multiple condition with various comparision operators). Meaning that, i will not be knowing operator presidance while coding.

e.g.
((1==i)&&((2==j)||(1<=k)))
((1==i)&&((2==j)||(1>=k)))

ANSWER: Hello Prasad

It cannot be done easily. It is not part of the language. You need to parse the string and interpret it. You need to learn how to write interpreters, and that is the subject of entire books.

There is one ugly way of doing it, but it requires that the computer running the program also have a compiler installed. Essentially, your program writes another function, and your program runs the compiler. The function is compiled into a dll or shared library. Your program then opens the library, finds the function, and executes it. I don't think that's what you want to do.

Best regards
Zlatko

---------- FOLLOW-UP ----------

QUESTION: Hi Zlatko,
Thanks for your reply.
I do understand, i cannot get this resolved easily. Actually, let me brief you further on my sistuation.
I am writing code in C/C++, which generates the C/C++ code(whole project) and the generated code eventually runs. Now i can have the values only at runtime and hence i am creating string which will have values at runtime only. That string i am using in if condition.
I cannot have the condition string with values other than at runtime. So i dont see any other way than evaluating the string at runtime in if condition. You can suggest any other way if you think of.
It would be of great help if you have any code for that.

Answer
Hello Prasad

It still seems to me that you need to write an interpreter to evaluate the "C" code at runtime. There are tools to make the job easier. You can use a tool called lex, or flex, to scan the string and break it into tokens. You can use a tool called yacc, or bison, to parse the tokens according to a grammar. Do an internet search on bison and interpreter. Here is one site I found that looks promising.
http://www.alanmacek.com/software/interpreter/

I have not done any work with those tools, but I used to work with a person who does, and he says the tools are very good.

Best regards
Zlatko.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.