Search code examples
cgetchar

How does "getchar()" know what character to read in C?


I have just started learning C and I came across an example which used the function getchar in a while loop. I don't understand how the getchar knows which char to return if it takes in no parameters. It was used in a way similar to this:

int c;
while((c = getchar()) != EOF){
    putchar(c);
}

Solution

  • Firstly, take note of the function prototype:

    int getchar(void);
    

    The getchar() function always reads the next character from the standard input stream.

    It doesn't need any arguments because it only ever does that one thing. In particular, observe from the documentation:

    The getchar() function shall be equivalent to getc(stdin).

    So getchar() is really the same as getc(), only that getc() allows you to specify the input stream.

    Your confusion lies in the fact that the getchar() function has no explicit input parameters (in the form of function arguments -- its a void function) and yet it can return all sorts of different results to you.

    Its "input" depends on the user input instead, much like scanf(), fgets() and even command-line arguments through the argv array.