Search code examples
csignalspostfix-notation

C programming switch statements to find a number or a letter


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;
}

Solution

  • The C preprocessor performs textual replacement before the compiler reads and parses your source code. NUMBER is replaced with '0' which is the value of the character representing the digit 0.

    The function getop() probably returns the value '0' when a number is parsed from the input and copies the digits to s. atof() converts that to a number.

    If you have access to the source code for getop(), you will see how it parses numbers, white space, comments and operators.

    Note that you should not use % with floating point values. You should use fmod() instead.