Skip to content

Commit 74a8a2e

Browse files
author
Joshua Goller
committed
5.10 test cases
1 parent dc856cd commit 74a8a2e

File tree

2 files changed

+23
-11
lines changed

2 files changed

+23
-11
lines changed

ch-5/Makefile

+13-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,19 @@ ifdef RUN_TESTS
2626
endif
2727

2828
5.8-9: 5.8-9-build 5.8-9-basic-test
29-
5.10: 5.10-build 5.10-basic-test
29+
5.10: 5.10-build
30+
ifdef RUN_TESTS
31+
$(VALGRIND) ./bin/$@ 10 5 +
32+
$(VALGRIND) ./bin/$@ 10 5 /
33+
$(VALGRIND) ./bin/$@ 5 10 -
34+
$(VALGRIND) ./bin/$@ 5 10 "*"
35+
@# ((10 5 +) + (10 / 5)) + ((5 10 -) + (5 10 *))
36+
$(VALGRIND) ./bin/$@ 10 5 + 10 5 / + 5 10 - 5 10 "*" + +
37+
@# tests that should cause exceptions
38+
-$(VALGRIND) ./bin/$@ 10 5 %
39+
-$(VALGRIND) ./bin/$@ herp derp ferp
40+
-$(VALGRIND) ./bin/$@
41+
endif
3042

3143
# tabber covers the entab / detab exercises in 5.11 and 5.12
3244
tabber: clean

ch-5/src/5.10.c

+10-10
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
1-
#include "5.10.h"
21
#include <ctype.h>
32
#include <stdio.h>
43
#include <stdlib.h>
54

65
/*
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)".
109
*/
1110

1211
#define MAX_SIZE 100
1312

1413
static int top = -1;
1514
static int stack[MAX_SIZE];
1615

17-
void push(int val) {
16+
static void push(const int val) {
1817
if (top >= MAX_SIZE - 1) {
1918
printf("Error: stack full, cannot push more values.\n");
2019
}
2120
stack[++top] = val;
2221
}
2322

24-
int pop() {
23+
static int pop(void) {
2524
int ret;
2625
if (top == -1) {
2726
printf("Error: stack empty.\n");
@@ -31,14 +30,15 @@ int pop() {
3130
return ret;
3231
}
3332

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) {
3535
for (int i = 0; num_string[i] != '\0'; i++) {
3636
if (!(isdigit(num_string[i]))) {
37-
return 0;
37+
return -1;
3838
}
3939
}
4040
*val = atoi(num_string);
41-
return 1;
41+
return 0;
4242
}
4343

4444
int main(int argc, char* argv[]) {
@@ -47,7 +47,7 @@ int main(int argc, char* argv[]) {
4747
char* current_arg = argv[i];
4848
int arg_val;
4949

50-
if (is_number(current_arg, &arg_val)) {
50+
if (to_number(current_arg, &arg_val) == 0) {
5151
push(arg_val);
5252
} else {
5353
switch (*(current_arg)) {

0 commit comments

Comments
 (0)