-
Notifications
You must be signed in to change notification settings - Fork 0
/
expr.c
46 lines (42 loc) · 1.04 KB
/
expr.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "expr.h"
#include <stdlib.h>
Expr* create_constant_expression(float value)
{
Expr* e = malloc(sizeof(Expr));
e->left = NULL;
e->right = NULL;
e->op = '\0';
e->value = value;
}
Expr* create_arithmetic_expression(Expr* e1, Expr* e2, char op)
{
Expr* e = malloc(sizeof(Expr));
e->left = e1;
e->right = e2;
e->op = op;
e->value = 0;
return e;
}
float evaluate_expression(Expr* e)
{
switch(e->op) {
case '+':
return evaluate_expression(e->left) + evaluate_expression(e->right);
break;
case '-':
return evaluate_expression(e->left) - evaluate_expression(e->right);
break;
case '*':
return evaluate_expression(e->left) * evaluate_expression(e->right);
break;
case '/':
return evaluate_expression(e->left) / evaluate_expression(e->right);
break;
case '\0':
return e->value;
break;
default:
return 0;
break;
}
}