This is typically done with a recursive function like this:
double eval_expr(expr_node *expr, var_state *vars) {
switch (expr->type) {
case EXPR_VAR: return read_variable(var_state, expr->var_name);
case EXPR_CONST: return expr->const_value;
case EXPR_OP:
switch (expr->op->op_name) {
case OP_ADD: return eval_expr(expr->left, vars) + eval_expr(expr->right, vars);
case OP_MUL: return eval_expr(expr->left, vars) * eval_expr(expr->right, vars);
..... and so on
}
}
}
There are also nice ways to do it using objects and polymorphism.
class VarState {
double var_value(string varname) {.....}
}
abstract class ExprNode {
abstract double eval(VarState state);
}
class AddNode {
ExprNode mLeft, mRight;
AddNode(ExprNode left, ExprNode right) {
mLeft = left;
mRight = right;
}
double eval(VarState state) {
return mLeft.eval(state) + mRight.eval(state);
}
}
Main Topics
Browse All Topics





by: NovaDenizenPosted on 2009-02-26 at 09:33:57ID: 23747180
You're trying to compile the expression into a series of operations with only one temporary variable. You can't do that for expressions in general. You need a stack or some form of recursion so that you can support an arbitrary number of temporary variables.