Question

The buf array will never have more than one element, because of getop's implementation. So, couldn't it be declared as an ordinary char variable?

This is the source code of the program, pages 74 - 79:

#include <ctype.h>

int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[]) /* we pass s[] to getop to store input */
{
    int i, c;

    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';
    if (!isdigit(c) && c != '.')
        return c; /* not a number */
    i = 0;
    if (isdigit(c)) /* collect integer part */
        while (isdigit(s[++i] = c = getch()))
            ;
    if (c == '.') /* collect fraction part */
        while (isdigit(s[++i] = c = getch()))
            ;
    s[i] = '\0';
    if (c != EOF)
        ungetch(c);
    return NUMBER;
}

#define BUFSIZE 100

char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0;
/* getch: the function which actually gets chars! */
int getch(void) /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back in input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}
Was it helpful?

Solution

A few paragraphs after the discussion of getop(), the book has this to say about the ungetch() implementation (emphasis added):

The standard library includes a function ungetch that provides one character of pushback; we will discuss it in Chapter 7. We have used an array for the pushback, rather than a single character, to illustrate a more general approach.

OTHER TIPS

BUFSIZE could be 1 if getop() is the only function to call ungetch().

Based on this post, the higher level code may have called ungetch() multiple times before calling getop(), thus filling more than 1 char into buf.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top