Hello everyone I was trying the questions from the C programming language book by by Brian W. Kernighan (Author), Dennis M. Ritchie (Author).The book provides the code for a basic reverse Polish Calculator but I do not understand how #define NUMBER '0'
works with the switch statement:
How is it able to capture all the numbers although we did not have case for each number. Also the next questions asks me to handle cases like sin
, cos
or pow
. I am assuming there is also a similar way to do it but if explained would help me better.
The getop
gets next operator or numeric operand, push
and pop
are regular stack functions and atof
converts ascii to floats.
#define NUMBER '0'
int type;
double op2;
char s[100];
while ((type = getop(s)) != EOF) {
switch (type) {
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error: zero divisor\n");
break;
case '%':
op2 = pop();
if (op2 != 0.0)
push((int)pop() % (int)op2);
else
printf("error: division by zero\n");
break;
case '\n':
printf("\t%.8g\n", pop());
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
}