-
Why do we write *bufp = buf since both are arrays so in my opinion it should be:
static char bufp = buf; -
How does *bufp “know” from which position to start displaying ? It is not initialized to zero in any way. After assigning
buftobufpI’d expect that in return line it starts with the last entered char. -
Is unsigned char modifier used here just to omit the case of
-1being the input – meaningEOFon most systems?
#include "syscalls.h"
/* getchar: simple buffered version */
int getchar(void)
{
static char buf[BUFSIZ];
static char *bufp = buf; /* [1] */
static int n = 0;
if (n == 0) { /* buffer is empty */
n = read(0, buf, sizeof buf);
bufp = buf; /* ? [1] here it is written like in my question so which is true ? */
}
return (--n >= 0) ? (unsigned char) *bufp++ : EOF; /* [2] & [3] */
}
[1]
char bufp = bufis incorrect, as buf is an array of char (and is internally an address, i.e. the content of a pointer), andchar bufpwould declare a unique character.char *bufp, instead, is a pointer to a char (to the first char, but you can access the next ones also).[2]
bufppoints to thebufarray, ie its first character, at the beginning. Andnis set to0.bufp,bufandnare all static, meaning they “live” after the function returns – each of their value is initialized when the program loads, then the initialization is not performed anymore each time the function is called. Thus they “remember” the status of the buffer:So to answer your [2] question,
readfills the bufferbufandbufppoints to the beginning of that array.*bufpis the next character to be returned ;*bufp++gives the character to be returned and increments thebufppointer by one.[3] The
unsignedmodifier prevents the compiler to propagate the*bufpcharacter (8 bits) sign to theintother bytes (usually 32 bits, ie the 24 most significant bits), since anintis returned. Thus any character where code would be > 127 (for unsigned chars, or negative for signed char) is returned as is (eg (unsigned char)200 is returned as (int)200).