-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.10.c
98 lines (92 loc) · 2.42 KB
/
5.10.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK 10 /* size of stack */
int
main(int argc, char **argv)
{
int stack[STACK] = {0};
int *sp = &stack[0];
int a, b;
for (++argv; *argv != NULL; ++argv) {
switch (*(*argv)) { /* first byte of argv[1] */
case '0': case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
negative_number:
if (sp >= stack + STACK) {
fprintf(stderr, "error: stack full\n");
break;
}
*sp++ = atoi(*argv);
break;
case '+':
if (sp - stack < 2) {
fprintf(stderr, "error: <2 operands stacked\n");
break;
}
a = *--sp;
a += *--sp;
*sp++ = a;
break;
case '*': case 'x':
if (sp - stack < 2) {
fprintf(stderr, "error: <2 operands stacked\n");
break;
}
a = *--sp;
a *= *--sp;
*sp++ = a;
break;
case '-':
if (*(*argv + 1) != '\0') /* next byte of argument */
goto negative_number;
if (sp - stack < 2) {
fprintf(stderr, "error: <2 operands stacked\n");
break;
}
a = *--sp;
b = *--sp;
*sp++ = b - a;
break;
case '/':
if (sp - stack < 2) {
fprintf(stderr, "error: <2 operands stacked\n");
break;
}
if (*(sp - 1)) { /* check that divisor is not zero */
a = *--sp;
b = *--sp;
*sp++ = b / a;
break;
}
fprintf(stderr, "error: divide by zero\n");
break;
default:
fprintf(stderr, "invalid input: %s\n", *argv);
break;
}
}
printf("%d\n", *stack); /* *stack or *--sp? ... */
int i;
for (i = 0, sp = &stack[0]; i < STACK; ++i, *++sp) {
fprintf(stderr, "%d %d\n", i, *sp);
}
return 0;
}
/*
While there are input tokens left
Read the next token from input.
If the token is a value
Push it onto the stack.
Otherwise, the token is an operator (operator here includes both operators and functions).
It is known a priori that the operator takes n arguments.
If there are fewer than n values on the stack
(Error) The user has not input sufficient values in the expression.
Else, Pop the top n values from the stack.
Evaluate the operator, with the values as arguments.
Push the returned results, if any, back onto the stack.
If there is only one value in the stack
That value is the result of the calculation.
Otherwise, there are more values in the stack
(Error) The user input has too many values.
*/