Question

I have a big problem understanding several lines from the following code (numbers marked in comments):

First - the code of a loop that fills an array with the input data:

int n, array[SIZE], getint(int *);
for (n = 0; n < SIZE && getint(&array[n]) != EOF; n++)
      ;

Now the function definition:

/* 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); /* [1] */ /* it is not a number */
        return 0;  /* [2] */
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
        c = getch();
for (*pn = 0; isdigit(c); c = getch())
        *pn = 10 * *pn + (c - '0'); [3]
*pn *= sign;
if (c != EOF) /* [4a] */
        ungetch(c); /* [4b] */
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;
}

So:

[1] I've read similar posts here, that taking back such an unwanted char somehow blocks the buffer, so that we need to clear it using another function. For me it's strange that is not included in K&R and authors don't even mention the necessity to use it?

[2] Why do we return 0? Does that stop the whole main() program? Or does it simply put 0 in an array ? ( getint(&array[n] ) ?

[3] Why do we need to implement such a formula to calculate "big numbers" ? Since that function just gets numbers one after the other (getchar not getword) and then create "big number" by means of several single integers.

[4a][4b] Why does it ungetch if c != EOF? This condition is fulfilled most of the time, so we would end up with rejecting every inputted number?

Thanks in advance for answering!

Was it helpful?

Solution

  1. It doesn't, and even if it did with some other library, not with these 2 functions
  2. Nope. It simply returns zero and leaves the integer uninitialized (this case isn't handled in the loop)
  3. What do you mean? This is simply how you calculate an integer from it's digits.
  4. It will simply ungetch the character that was trailing the integer the function just read and processed - unless there was no character but an end of stream marked by EOF. That marker isn't returned to the buffer.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top