1
- #include "5.10.h"
2
1
#include <ctype.h>
3
2
#include <stdio.h>
4
3
#include <stdlib.h>
5
4
6
5
/*
7
- Write the program expr(), which evaluates a reverse polish expression from the
8
- command line, where each operator and operand is a separate argument. For
9
- example, "expr 2 3 4 + *" evaluates "2 x (3 + 4)".
6
+ Ex. 5.10: Write the program expr(), which evaluates a reverse polish expression
7
+ from the command line, where each operator and operand is a separate argument.
8
+ For example, "expr 2 3 4 + *" evaluates "2 x (3 + 4)".
10
9
*/
11
10
12
11
#define MAX_SIZE 100
13
12
14
13
static int top = -1 ;
15
14
static int stack [MAX_SIZE ];
16
15
17
- void push (int val ) {
16
+ static void push (const int val ) {
18
17
if (top >= MAX_SIZE - 1 ) {
19
18
printf ("Error: stack full, cannot push more values.\n" );
20
19
}
21
20
stack [++ top ] = val ;
22
21
}
23
22
24
- int pop () {
23
+ static int pop (void ) {
25
24
int ret ;
26
25
if (top == -1 ) {
27
26
printf ("Error: stack empty.\n" );
@@ -31,14 +30,15 @@ int pop() {
31
30
return ret ;
32
31
}
33
32
34
- int is_number (char * num_string , int * val ) {
33
+ // to_number(): like atoi() but with better validation
34
+ static int to_number (const char * const num_string , int * const val ) {
35
35
for (int i = 0 ; num_string [i ] != '\0' ; i ++ ) {
36
36
if (!(isdigit (num_string [i ]))) {
37
- return 0 ;
37
+ return -1 ;
38
38
}
39
39
}
40
40
* val = atoi (num_string );
41
- return 1 ;
41
+ return 0 ;
42
42
}
43
43
44
44
int main (int argc , char * argv []) {
@@ -47,7 +47,7 @@ int main(int argc, char* argv[]) {
47
47
char * current_arg = argv [i ];
48
48
int arg_val ;
49
49
50
- if (is_number (current_arg , & arg_val )) {
50
+ if (to_number (current_arg , & arg_val ) == 0 ) {
51
51
push (arg_val );
52
52
} else {
53
53
switch (* (current_arg )) {
0 commit comments