Exercise 4-9

Our getch and ungetch do not handle a pushed-back EOF correctly. Decide what their properties ought to be if an EOF is pushed back, then implement your design.

The reason why the two functions may not be able to handle a pushed-back EOF is because EOF is not a character, but buf is declared as a character array (note that the functions may still work on C implementations that use signed chars.) Thus, we change buf to be an integer array to retain the ability to push back an EOF on all systems.

    ...
    int sp = 0;         /* next free stack position */
    double val[MAXVAL]; /* value stack */
    double vars[26];    /* variable values */
    char buf[BUFSIZE];  /* buffer for ungetch */
    int buf[BUFSIZE];   /* buffer for ungetch */
    int bufp = 0;       /* next free position in buf */
    ...