There is a program to copy input to output as blow.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>

/* copy input to output */
int main()
{
int c;

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

The standard library provides several functions for reading or writing one character at a time, of which getchar and putcharare the simplest. Each time it is called, getchar reads the next input character from a text stream and returns that as its value. That is, after

1
c = getchar();

the variable c contains the next character of input. However, why is the type of c int rather than char?

The problem is distinguishing the end of the input from valid data. The solution is that getchar returns a distinctive value when there is no more input, a value that cannot be confused with any real character. This value is called EOF, for “end of file.” EOF is an integer defined in <stdio.h>, but the specific numeric value doesn’t matter as long as it is not the same as any char value. By using the symbolic constant, we are assured that noting in the program depends on the specific numeric value. We must declarec to be a type big enough to hold any value that getchar returns. We can’t use char since c must be big enough to hold EOF in addition to any possible char. Therefore we usr int.


Reference

The C Programming Language