IsmatS commited on
Commit
65bc3ac
·
1 Parent(s): 656b8d0

Create compiler.c

Browse files
Files changed (1) hide show
  1. compiler.c +84 -0
compiler.c ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <stdio.h>
2
+ #include <stdlib.h>
3
+ #include <ctype.h>
4
+
5
+ int expr();
6
+ int term();
7
+ int factor();
8
+ void error();
9
+
10
+ char token;
11
+
12
+ void next_token() {
13
+ token = getchar();
14
+ }
15
+
16
+ void match(char expected_token) {
17
+ if (token == expected_token) {
18
+ next_token();
19
+ } else {
20
+ error();
21
+ }
22
+ }
23
+
24
+ void error() {
25
+ printf("Syntax error\n");
26
+ exit(1);
27
+ }
28
+
29
+ int expr() {
30
+ int result = term();
31
+ while (token == '+' || token == '-') {
32
+ char op = token;
33
+ next_token();
34
+ if (op == '+') {
35
+ result += term();
36
+ } else {
37
+ result -= term();
38
+ }
39
+ }
40
+ return result;
41
+ }
42
+
43
+ int term() {
44
+ int result = factor();
45
+ while (token == '*' || token == '/') {
46
+ char op = token;
47
+ next_token();
48
+ if (op == '*') {
49
+ result *= factor();
50
+ } else {
51
+ int divisor = factor();
52
+ if (divisor != 0) {
53
+ result /= divisor;
54
+ } else {
55
+ error();
56
+ }
57
+ }
58
+ }
59
+ return result;
60
+ }
61
+
62
+ int factor() {
63
+ int result;
64
+ if (isdigit(token)) {
65
+ ungetc(token, stdin);
66
+ scanf("%d", &result);
67
+ next_token();
68
+ } else if (token == '(') {
69
+ next_token();
70
+ result = expr();
71
+ match(')');
72
+ } else {
73
+ error();
74
+ }
75
+ return result;
76
+ }
77
+
78
+ int main() {
79
+ printf("Enter an arithmetic expression: ");
80
+ next_token();
81
+ int result = expr();
82
+ printf("Result: %d\n", result);
83
+ return 0;
84
+ }