1 /* vi: set sw=4 ts=4: */
8 /* Tiny RPN calculator, because "expr" didn't give me bitwise operations. */
10 static const char math_usage[] = "math expression ...";
12 static double stack[100];
13 static unsigned int pointer;
15 static void push(double a)
17 if (pointer >= (sizeof(stack) / sizeof(*stack))) {
18 fprintf(stderr, "math: stack overflow\n");
27 fprintf(stderr, "math: stack underflow\n");
30 return stack[--pointer];
40 double subtrahend = pop();
42 push(pop() - subtrahend);
52 double divisor = pop();
54 push(pop() / divisor);
59 push((unsigned int) pop() & (unsigned int) pop());
64 push((unsigned int) pop() | (unsigned int) pop());
69 push((unsigned int) pop() ^ (unsigned int) pop());
74 push(~(unsigned int) pop());
79 printf("%g\n", pop());
87 static const struct op operators[] = {
99 static void stack_machine(const char *argument)
101 char *endPointer = 0;
103 const struct op *o = operators;
110 d = strtod(argument, &endPointer);
112 if (endPointer != argument) {
117 while (o->name != 0) {
118 if (strcmp(o->name, argument) == 0) {
124 fprintf(stderr, "math: %s: syntax error.\n", argument);
128 int math_main(int argc, char **argv)
131 stack_machine(argv[1]);