Below is a code snippet from Kerningham Ritchie book, chapter 8, section 8.2
#include "syscalls.h"
/* getchar: simple buffered version */
int getchar(void)
{
static char buf[BUFSIZ];
static char *bufp = buf;
static int n = 0;
if (n == 0) { /* buffer is empty */
n = read(0, buf, sizeof buf);
bufp = buf;
}
return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
}
I am not understanding why the bytes returned by read function stored in int n should be stored in a static int variable? How will in that case subsequent calls to getchar work? The read function is invoked only when n is equal to zero.
Can someone please explain?