Can't understand the working of getint() in C as per K&R

c

Solution

The getint() function only reads digits from the input. If it gets a character that is not a digit or a + - sign at the beginning it will call ungetch() to push the character back into the input buffer so it could be read by some other function call. getint() will go on returning 0 until you remove the non-digit character from the input buffer by calling getch() on your own.

Problem

I've been tried to understand the working of this code for 2 days now, but just can't wrap my head around it. My doubt is about the working of the function. Please don't take the absence of main or anything else into consideration. What I can't understand is that if getint() takes input with getchar() it will do the following: - Let's say bufp=0. The function will call getch(), which means c=a. (Just a random character) - The next step with ungetch(a), which means buf[0]=a and bufp=1. - Now this is where I can't get it. The next time getint() is called, c=buf[--bufp]=a and bufp=0 as a result. - This will then again ungetch(a), which will result lead the function nowhere! I don't know if I have some major concept(s) wrong here, but I just can't figure it out. :( ``` /* getint: get next integer from input into *pn */ int getint(int *pn) { int c, sign; while (isspace(c = getch())) /* skip white space */ ; if (!isdigit(c) && c != EOF && c != '+' && c != '-') { ungetch(c); /* it is not a number */ return 0; } sign = (c == '-') ? -1 : 1; if (c == '+' || c == '-') c = getch(); for (*pn = 0; isdigit(c); c = getch()) *pn = 10 * *pn + (c - '0'); *pn *= sign; if (c != EOF) ungetch(c); return c; } #define BUFSIZE 100 char buf[BUFSIZE]; /* buffer for ungetch */ int bufp = 0; /* next free position in buf */ int getch(void) /* get a (possibly pushed-back) character */ { return (bufp > 0) ? buf[--bufp] : getchar(); } void ungetch(int c) /* push character back on input */ { if(bufp >= BUFSIZE) printf(" ungetch too many characters\n"); else buf[bufp++] = c; } ```

Original source