ZetCode

The reverse Polish calculator in K&R C

last modified December 5, 2026 K&R C 1978

The calculator is the best-known program of the book. It reads expressions in reverse Polish notation, where each operator follows its operands: (1 - 2) * (4 + 5) is written 1 2 - 4 5 + *. No parentheses are needed, and the program needs no grammar: numbers go on a stack, and an operator takes its operands from the top of the stack and pushes the result back. This article builds the calculator from its parts, splits it into files, makes it recover from bad input, and runs it on the PDP-11.

The stack

The stack is an array and an index to its next free position. Both are external variables, because two functions use them and neither of them owns the stack: push stores a value and pop takes the last one off again.

stack1.c
#include <stdio.h>

#define MAXVAL 100      /* depth of the stack */

int sp = 0;             /* next free position */
double val[MAXVAL];     /* the values */

int push(f)
double f;
{
    val[sp++] = f;
    return 0;
}

double pop()
{
    return val[--sp];
}

/* compute 1 2 - 4 5 + * by hand */
int main()
{
    double op2;

    push(1.0);
    push(2.0);
    op2 = pop();
    push(pop() - op2);
    push(4.0);
    push(5.0);
    push(pop() + pop());
    push(pop() * pop());
    printf("%g\n", pop());
    return 0;
}

main computes 1 2 - 4 5 + * by hand, with the calls the calculator will make. A number is pushed. The minus pops its second operand first, so it is saved in op2 before the first one is popped; for + and * the order does not matter. The arguments are written 1.0, not 1: nothing converts an int argument to the double parameter, as the functions article showed. pop is defined before main, so the compiler knows that it returns a double.

$ gcc -std=c89 -pedantic -Wall -Wextra -o stack1 stack1.c
$ ./stack1
-9

Checking the stack

The first version trusts its input. Too many pushes run past the end of the array, and a pop from an empty stack reads val[-1]. The calculator works on whatever the user types, so its stack must check both cases.

stack2.c
#include <stdio.h>

#define MAXVAL 3        /* a small stack for the test */

int sp = 0;
double val[MAXVAL];

int push(f)
double f;
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, %g not pushed\n", f);
    return 0;
}

double pop()
{
    if (sp > 0)
        return val[--sp];
    printf("error: stack empty\n");
    return 0.0;
}

int clear()
{
    sp = 0;
    return 0;
}

int main()
{
    push(1.0);
    push(2.0);
    push(3.0);
    push(4.0);
    printf("%g\n", pop());
    clear();
    printf("%g\n", pop());
    return 0;
}

push refuses a value when the stack is full, and pop reports an empty stack and returns zero, so the caller always gets a number. clear empties the stack by resetting the index; the values stay in the array but can no longer be reached. MAXVAL is 3 here, so the fourth push fails.

$ gcc -std=c89 -pedantic -Wall -Wextra -o stack2 stack2.c
$ ./stack2
error: stack full, 4 not pushed
3
error: stack empty
0

Reading operators and operands

The input is a sequence of numbers, operators, and newlines. A function called getop reads the next one. To know that a number has ended, it must read the character after it, which may be an operator written without a blank, as in 3.5+. That character must go back to the input, so the program has its own push-back buffer, as the character input article did with ungetc.

tokens.c
#include <stdio.h>
#include <ctype.h>

#define MAXOP   20      /* longest operand */
#define NUMBER  '0'     /* getop found a number */
#define TOOBIG  '9'     /* getop found a number that is too long */
#define BUFSIZE 100

char buf[BUFSIZE];      /* characters pushed back */
int bufp = 0;           /* next free position in buf */

int getch()             /* the next character, pushed back or new */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

int ungetch(c)          /* push a character back on the input */
int c;
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
    return 0;
}

/* read the next operator or operand into s */
int getop(s, lim)
char s[];
int lim;
{
    int c, i;

    while ((c = getch()) == ' ' || c == '\t')
        ;
    if (c != '.' && !isdigit(c))
        return c;
    s[0] = c;
    for (i = 1; (c = getch()) == '.' || isdigit(c); i++)
        if (i < lim - 1)
            s[i] = c;
    if (c != EOF)
        ungetch(c);
    if (i >= lim - 1) {
        s[lim - 1] = '\0';
        return TOOBIG;
    }
    s[i] = '\0';
    return NUMBER;
}

int main()
{
    int type;
    char s[MAXOP];

    while ((type = getop(s, MAXOP)) != EOF)
        if (type == NUMBER)
            printf("number %s\n", s);
        else if (type == TOOBIG)
            printf("too long %s\n", s);
        else if (type == '\n')
            printf("newline\n");
        else
            printf("operator %c\n", type);
    return 0;
}

getch returns a pushed-back character if there is one and reads a new character otherwise; ungetch pushes a character back. The buffer can hold many characters, although the calculator never pushes back more than one. getop skips blanks and tabs and returns any other character that cannot start a number as itself. For a number it collects digits and points, stores them in s, and returns the code NUMBER. A number longer than the array is read to its end but not stored, and getop returns TOOBIG with the part that fitted. The codes '0' and '9' are digits, so no operator can be mistaken for them.

input.txt
12 3.5+ x
1234567890123456789012 *

The test input has a number glued to an operator, a letter, and a number with 22 digits.

$ gcc -std=c89 -pedantic -Wall -Wextra -o tokens tokens.c
$ ./tokens < input.txt
number 12
number 3.5
operator +
operator x
newline
too long 1234567890123456789
operator *
newline

The calculator in files

The complete program is too large for one listing, and its parts are independent: the stack, the input functions, and the main loop. It is split into four source files and a header that they share, as the program structure article described.

calc.h
#define MAXOP   20      /* longest operand */
#define NUMBER  '0'     /* getop found a number */
#define TOOBIG  '9'     /* getop found a number that is too long */

int push(), clear(), depth(), getop(), getch(), ungetch();
double pop();

The header defines the constants and declares the functions. Every function that is called from another file is declared, so the compiler knows that pop returns a double and does not need to assume an int for the others.

stack.c
#include <stdio.h>

#define MAXVAL 100      /* depth of the stack */

int sp = 0;             /* next free position */
double val[MAXVAL];     /* the values */

int push(f)
double f;
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, %g not pushed\n", f);
    return 0;
}

double pop()
{
    if (sp > 0)
        return val[--sp];
    printf("error: stack empty\n");
    return 0.0;
}

int clear()
{
    sp = 0;
    return 0;
}

int depth()             /* the number of values on the stack */
{
    return sp;
}

The stack is the checked version from before, with one more function: depth returns the number of values on the stack. The main loop uses it later in this article. The variables sp and val are external, but only the functions of this file use them.

getch.c
#include <stdio.h>

#define BUFSIZE 100

char buf[BUFSIZE];      /* characters pushed back */
int bufp = 0;           /* next free position in buf */

int getch()             /* the next character, pushed back or new */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

int ungetch(c)          /* push a character back on the input */
int c;
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
    return 0;
}

The push-back buffer lives in its own file with the two functions that use it.

getop.c
#include <stdio.h>
#include <ctype.h>
#include "calc.h"

/* read the next operator or operand into s */
int getop(s, lim)
char s[];
int lim;
{
    int c, i;

    while ((c = getch()) == ' ' || c == '\t')
        ;
    if (c != '.' && !isdigit(c))
        return c;
    s[0] = c;
    for (i = 1; (c = getch()) == '.' || isdigit(c); i++)
        if (i < lim - 1)
            s[i] = c;
    if (c != EOF)
        ungetch(c);
    if (i >= lim - 1) {
        s[lim - 1] = '\0';
        return TOOBIG;
    }
    s[i] = '\0';
    return NUMBER;
}

getop is unchanged. It includes calc.h for NUMBER, TOOBIG, and the declarations of getch and ungetch.

main.c
#include <stdio.h>
#include <stdlib.h>
#include "calc.h"

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];

    while ((type = getop(s, MAXOP)) != 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 'c':
            clear();
            break;
        case '\n':
            printf("%.8g\n", pop());
            break;
        case TOOBIG:
            printf("error: %s... is too long\n", s);
            break;
        default:
            printf("error: unknown command %c\n", type);
            break;
        }
    return 0;
}

The main loop is a switch on the value that getop returns. A number is converted with atof and pushed. Each operator pops its operands and pushes the result; division checks for a zero divisor first. The command c clears the stack. A newline ends an expression, and its result is popped and printed with %.8g, which prints up to eight significant digits and no trailing zeros.

exprs.txt
1 2 - 4 5 + *
3 4 2 * 1 5 - / +
10 3 /
2.5 4 * 0.5 +

Each line of the input file is one expression. The second is 3 + 4 * 2 / (1 - 5), and the last pushes two results before it adds them.

$ gcc -std=c89 -pedantic -Wall -Wextra -o calc main.c stack.c getop.c getch.c
$ ./calc < exprs.txt
-9
1
3.3333333
10.5

Errors in the input

The calculator reports bad input, but it does not recover from it. After an error, the rest of the line is still evaluated, and whatever was left on the stack goes into the next result.

errors.txt
1 +
1 0 / 5 +
2 x 3 +
123456789012345678901234 1 +
1 2 3 +
7 2 -

Each line of the file has one mistake: a missing operand, a zero divisor, an unknown command, a number that is too long, too many operands, and finally a correct expression.

In the run, every error is reported, but the evaluation goes on. 1 + pops 1 and then an empty stack, adds 1 and 0, and prints 1. After the zero divisor, the 1 left on the stack is added to 5, and the line prints 6 instead of failing. The letter is skipped, so 2 x 3 + prints 5. After the too long number, 1 + pops an empty stack again. 1 2 3 + prints 5 and leaves 1 on the stack, where it stays under every later result. The last line happens to print the right answer, but none of the numbers before it can be trusted.

$ ./calc < errors.txt
error: stack empty
1
error: zero divisor
6
error: unknown command x
5
error: 1234567890123456789... is too long
error: stack empty
1
5
5

Recovering from errors

A better calculator abandons the whole expression after an error: it skips the rest of the line and empties the stack. It also checks the depth of the stack before an operator, so that an empty stack is found before anything is popped. Only main.c changes.

main.c
#include <stdio.h>
#include <stdlib.h>
#include "calc.h"

/* skip the rest of the line and empty the stack */
int skipline()
{
    int c;

    while ((c = getch()) != '\n' && c != EOF)
        ;
    clear();
    return 0;
}

/* reverse Polish calculator that recovers from errors */
int main()
{
    int type;
    double op1, op2;
    char s[MAXOP];

    while ((type = getop(s, MAXOP)) != EOF)
        switch (type) {
        case NUMBER:
            push(atof(s));
            break;
        case '+':
        case '-':
        case '*':
        case '/':
            if (depth() < 2) {
                printf("error: %c needs two operands\n", type);
                skipline();
                break;
            }
            op2 = pop();
            op1 = pop();
            if (type == '+')
                push(op1 + op2);
            else if (type == '-')
                push(op1 - op2);
            else if (type == '*')
                push(op1 * op2);
            else if (op2 != 0.0)
                push(op1 / op2);
            else {
                printf("error: zero divisor\n");
                skipline();
            }
            break;
        case '\n':
            if (depth() == 1)
                printf("%.8g\n", pop());
            else if (depth() > 1) {
                printf("error: %d values left\n", depth());
                clear();
            }
            break;
        case TOOBIG:
            printf("error: %s... is too long\n", s);
            skipline();
            break;
        default:
            printf("error: unknown command %c\n", type);
            skipline();
            break;
        }
    return 0;
}

The four operators share one case: the code checks that two operands are there, pops them, and chooses the operation. Every error calls skipline, which reads up to the end of the line with getch, so that a pushed-back character is not lost, and clears the stack. The newline prints a result only if exactly one value is left; more values mean that operators were missing. The same input file now gives one message per bad line and the right result for the last one.

$ gcc -std=c89 -pedantic -Wall -Wextra -o calc main.c stack.c getop.c getch.c
$ ./calc < errors.txt
error: + needs two operands
error: zero divisor
error: unknown command x
error: 1234567890123456789... is too long
error: 2 values left
5

Negative numbers

The calculator cannot read a negative number: -3 is the minus operator followed by 3. A minus sign starts a number only when a digit or a point follows it directly, and getop can find that out by reading one character ahead.

getop.c
#include <stdio.h>
#include <ctype.h>
#include "calc.h"

/* read the next operator or operand into s; a minus sign
   directly before a digit or a point starts a number */
int getop(s, lim)
char s[];
int lim;
{
    int c, next, i;

    while ((c = getch()) == ' ' || c == '\t')
        ;
    if (c == '-') {
        next = getch();
        ungetch(next);
        if (next != '.' && !isdigit(next))
            return c;
    } else if (c != '.' && !isdigit(c))
        return c;
    s[0] = c;
    for (i = 1; (c = getch()) == '.' || isdigit(c); i++)
        if (i < lim - 1)
            s[i] = c;
    if (c != EOF)
        ungetch(c);
    if (i >= lim - 1) {
        s[lim - 1] = '\0';
        return TOOBIG;
    }
    s[i] = '\0';
    return NUMBER;
}

When getop sees a minus, it reads the next character and pushes it back at once. If it is not a digit or a point, the minus is the operator. Otherwise the minus becomes the first character of the number, and atof converts -3 like any other number. 5 -2 - subtracts -2 from 5, and 10 4 - -1 - uses the minus both ways.

numbers.txt
-3 4 *
5 -2 -
10 4 - -1 -
1 2 /
-.5 3 /
100000 3 *

The input also has a fraction, a negative number that starts with a point, and a result with six digits.

$ gcc -std=c89 -pedantic -Wall -Wextra -o calc main.c stack.c getop.c getch.c
$ ./calc < numbers.txt
-12
7
7
0.5
-0.16666667
300000

The calculator on the PDP-11

The calculator was written for the PDP-11, and its five files compile there without a change. cc prints the name of each file as it compiles it.

The calculator computes the same results, but the V7 printf writes some of them differently. %g leaves out the zero before the decimal point, so one half is .5, and it switches to exponent notation at 100000 even when the precision would allow all the digits: 300000 is printed as 3.e+05. The formatted output article shows more of these differences.

$ cc main.c stack.c getop.c getch.c
main.c:
stack.c:
getop.c:
getch.c:
$ a.out < numbers.txt
-12
7
7
.5
-.16666667
3.e+05

Source

Dennis Ritchie: C Reference Manual (1975)

Reverse Polish notation on Wikipedia

In this article we have built the reverse Polish calculator of the book: a stack of double values, a reader for numbers and operators with its own push-back buffer, the program split into files with a shared header, recovery from bad input, negative numbers, and a run on the PDP-11. The next article covers sorting and searching.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.