Confused about getchar() function

Serenity picture Serenity · Mar 9, 2010 · Viewed 10.4k times · Source

I am confused about getchar()'s role in the following code. I mean I know it's helping me see the output window which will only be closed when I press the Enter key.

So getchar() is basically waiting for me to press enter and then reads a single character.

What is that single character this function is reading? I did not press any key from the keyboard for it to read.

Now when it's not reading anything, why does it not give an error saying "hey, you didn't enter anything for me to read"?

#include <stdio.h>

int main()
{
    printf( "blah \n" );
    getchar();
    return 0;
}

Answer

Luca Matteis picture Luca Matteis · Mar 9, 2010

That's because getchar() is a blocking function.

You should read about blocking functions, which basically make the process wait for something to happen.

The implementation of this waiting behavior depends on the function, but usually it's a loop that waits for some event to happen.

For the case of the getchar() function, this probably is implemented as a loop that constantly reads a file (stdin for this case) and checks weather the file is modified. If the file is modified, the loop behaves by doing something else.