Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

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

Writer Olivia Zamora

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:

  1. Let's say bufp=0. The function will call getch(), which means c=a. (Just a random character)
  2. The next step with ungetch(a), which means buf[0]=a and bufp=1.
  3. 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.
  4. 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;
}
2

4 Answers

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.

3

it makes sense to me you are confusing your function names

getch != getchar getint != getop

get some sleep

1

If getint() fails (and thus use ungetch in the scenario you give), calling again getint() will fail again. You are expected to call another function which will consume the pending character and make something usefull from the data which can't be interpreted as an int.

Functions will execute in the order in which they are called, rather than their order in a source file.

There is also no main(){...}, so the code won't do anything in its current state.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy