This is some sample code from The C Programming Language by Ritchie & Kernighan.
int c;
while((c=getchar())!=EOF) {
putchar(c);
}
Notice that putchar referes to a variable of type int. Why is it possible to return and display both characters and integers with this code?
An int
is usually represented by 4 bytes while a char
is actually just 1 byte of data. You can easily store a full character and more in the single int
that getchar()
returns. When an int is passed to putchar(int)
it just lops off the extra space before displaying it. This technique is useful for passing EOF
which is actually not a char
at all, but an int
that signals the end of the file.