Reputation: 483
int getch(void);
void ungetch(int);
/* getop: get next character or numeric operand */
int getop(char s[])
{
int i, c;
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
if (!isdigit(c) && c != '.')
return c; /* not a number */
i = 0;
if (isdigit(c)) /* collect integer part */
while (isdigit(s[++i] = c = getch()))
;
if (c == '.') /* collect fraction part */
while (isdigit(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF)
ungetch(c);
return NUMBER;
}
#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;
}
The above code is from K&R.
In the above code, I see the array buf[]
is used to a maximum of index 1, but it is defined to have a size of 100. Is the definition ok or there is a huge wastage in memory?
I pretty much think this is a bad style of programming.
I'm asking for getop() func only,not for general getch() and ungetch()
I'm a beginner and I'm sorry if my question is invalid :P
Upvotes: 2
Views: 109
Reputation: 46323
Disregarding the "style of programming", these are functions without anything to run them (ie. a main
function). As such, you can't tell how these will be used but you can understand how they can be used. Now, suppose ungetch
is called in a loop, without getch
being called at all. In each iteration, bufp
will grow by 1, and buf
will slowly fill up to the point where bufp
is equal to BUFSIZE
and the "too many characters" will be printed. Next, if getch
is called in a loop AFTER buf
is full, bufp
will shrink by 1 for each iteration untill buf
is empty and getchar
will be used for the next character.
Upvotes: 1