I’m reading the book “The C Programming Language” and there is an exercise that asked to verify that the expression getchar() != EOF is returning 1 or 0. Now the original code before I was asked to do that was:
int main()
{
int c;
c = getchar();
while (c != EOF)
{
putchar(c);
c = getchar();
}
}
So I thought changing it to:
int main()
{
int c;
c = getchar();
while (c != EOF)
{
printf("the value of EOF is: %d", c);
printf(", and the char you typed was: ");
putchar(c);
c = getchar();
}
}
And the answer in the book is:
int main()
{
printf("Press a key\n\n");
printf("The expression getchar() != EOF evaluates to %d\n", getchar() != EOF);
}
Could you please explain to me why my way didn’t work?
Because if
cisEOF, thewhileloop terminates (or won’t even start, if it is alreadyEOFon the first character typed). The condition for running another iteration of the loop is thatcis NOTEOF.