This code comes from K & R. I read it several times, but it still seems to me that I don't understand.
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return(bufp>0)?buf[--bufp]:getchar();
}
int ungetch(int c)
{
if(bufp>=BUFSIZE)
printf("too many characters");
else buf[bufp++]=c;
}
The purpose of these two functions, so K & R says, is to prevent the program from reading too much input. that is, without this code, the function may not be able to determine that it read enough data without first reading. But I do not understand how this works.
For example, consider getch (). As far as I can see, these are the steps that need to be completed:
- check that bufp is greater than 0.
- if so, return the value char buf [- bufp].
- else return getchar ().
I would like to ask a more specific question, but I literally donβt know how this code achieves what it is intended to achieve, so my question is: what is (a) the purpose and (b) the reasoning for this code
Thanks in advance.
. K & R . 79 ( , )
user485498