Getchar Function in C

Getchar Function in C


1

 

I don't understand the getchar function, or well really how it's laid out. I'm reading K&R and I feel as if it's going a bit too fast.

I understand EOF is end of file with an integer value of -1. Here's a piece of code:

#include <stdio.h>
/* copy input to output; 1st version */
main()
{
    int c;
    c = getchar();
    while (c != EOF) {
        putchar(c);
        c = getchar();
    }
}

What my current understanding is: We declare a variable called c that will be an integer, not a character because we can't fill the function with 1 byte only, so we use multiple, and this works because characters in C are stored in memory by their ASCII value(Please correct me if I'm wrong)

As for the while loop, is it there to keep the program running for multiple inputs? So the loop is saying, while variable c is not equal to the end of file we can receive input from getchar() to be fed to c, which we display using putchar(), then, the last c = getchar(); is to stall the program so it doesn't exit immediately?

The next program:

#include <stdio.h>
/* count characters in input; 1st version */
main()
{
    long nc;
    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%ld\n", nc);
}

As for declaring nc; for a long, why? We used integer before, and now we use long? I understand in some cases, long can store more value than an integer?

Why do we set nc = 0? As for the increment operator, I u