#include<stdio.h>
int main()
{
int c;
while((c=getchar())!=EOF)
putchar(c);
putchar(c); //2nd putchar
getch();
}
In the above code from the book 'C by Ritchie n Kernighan', the reason for declaring c
an int
variable is given as :
so that
c
may be able to hold the code ofEOF
which is outside the char codes which achar
datatype can accommodate.
But when I declare c as a char, and input the EOF
(CTRL-Z + Enter),that value(which is -1 on my computer)does go into c and I immediately end up exiting the while up, just the way it happens if I declare c as an int.
Why do we need to declare c as an int, when char works just fine?? or am I missing something here?
One more thing, in the second putchar
statement, it should print the last value of c (ie. -1) after having received EOF
but it doesn't. Why?