Unable to understand how getint () works in C according to K & R

I tried to understand the work of this code for 2 days, but I just can’t wrap it around me.

I doubt the function works. Please do not take into account the lack of basic or something else.

I do not understand that if getint () accepts input using getchar (), it will do the following:

  • Let's say bufp = 0. The function will call getch (), which means c = a. (Random character only)
  • The next step is with ungetch (a), which means buf [0] = a and bufp = 1.
  • Now I can’t get it. The next time getint () is called, c = buf [- bufp] = a and bufp = 0.
  • This will again disable (a), which will make the function unavailable!

I don't know if there are some basic concepts 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;
}
+3
4

getint() . , +, ungetch(), , . getint() 0 , , getch() .

+3

getch!= getchar getint!= getop

+1

getint() (, , ungetch ), getint() . , , - , int.

+1

, , .

Also not main(){...}, so the code will not do anything in the current state.

0
source

All Articles