diff options
Diffstat (limited to 'myfind/ast_evaluation/ast_evaluation.c')
| -rw-r--r-- | myfind/ast_evaluation/ast_evaluation.c | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/myfind/ast_evaluation/ast_evaluation.c b/myfind/ast_evaluation/ast_evaluation.c new file mode 100644 index 0000000..7ad91af --- /dev/null +++ b/myfind/ast_evaluation/ast_evaluation.c @@ -0,0 +1,29 @@ +#include <err.h>
+#include <stdio.h>
+
+#include "expression.h"
+
+int eval_expr(struct my_expr *expr)
+{
+ if (expr->type == EXPR_NUMBER)
+ return expr->data.value;
+ else if (expr->type == EXPR_NEGATION)
+ return -1 * eval_expr(expr->data.children.left);
+ else
+ {
+ int right = eval_expr(expr->data.children.right);
+ switch (expr->type)
+ {
+ case EXPR_ADDITION:
+ return eval_expr(expr->data.children.left) + right;
+ case EXPR_SUBTRACTION:
+ return eval_expr(expr->data.children.left) - right;
+ case EXPR_MULTIPLICATION:
+ return eval_expr(expr->data.children.left) * right;
+ default:
+ if (expr->data.children.right == NULL || (right == 0))
+ err(1, "Division by zero not allowed!");
+ return eval_expr(expr->data.children.left) / right;
+ }
+ }
+}
|
