As a newbie it is hard to reconcile bugs in the K&R text vs simply things that I do not understand. Also, sometimes the requirements for the sample programs are a little bit vague as to what exactly they are supposed to do.
However, both of those things said, I have been staring at getint() on page 87 for well over an hour, and running tests, and I am fairly certain there is a pretty large bug:
Code:
int getch(void);
void ungetch(int);
/* 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;
}
What happens here is if the character being "got" is not a number, it pushes it back to the input and returns zero. Then when the function is called again... it gets that same character, and does the same thing again. Forever. So it never gets past that character to the rest of the input.
I just want a sanity check from a more experienced C programmer to verify that my reasoning above is correct. Thanks!