问题
As written in book-
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." We must declare c 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 use int.
main()
{
int c;
c = getchar();
while(c != EOF) {
putchar(c);
c = getchar();
}
}
I am not able to understand the actual reason of using int instead of char. What will be returned by EOF such that cannot be stored in char.
回答1:
A char
can hold 256 different values (0 to 255). If EOF
was a char
, the value of EOF
would therefore be some value between 0 and 255, which would imply that there would be one character that you cannot read. Therefore the value of EOF
cannot be between 0 and 255, which implies that it cannot fit into a char
, which implies that its type must be larger than char
, for example an int
.
In other words EOF
is not a char
and we don't want to store it in a char
. It's only purpose is to enable a program to detect that one char beyond the end of the file has been attempted to read.
Or still in other words: let's suppose EOF
is defined as 255 and therefore fit's into a char
. Now let's suppose getchar
returns the value 255 (that is EOF
). Now what does that value represent? Is it an EOF
or is it the character 255?
来源:https://stackoverflow.com/questions/48870708/why-is-type-int-needed-to-handle-eof-and-return-of-getchar