So I'm reading K&R book and I have a question regarding this code:
int c;
c = getchar();
Why do they use integer variable? Isn't the value that getchar() returns a character? So a char would be more suitable? Please enlighten me.
So I'm reading K&R book and I have a question regarding this code:
int c;
c = getchar();
Why do they use integer variable? Isn't the value that getchar() returns a character? So a char would be more suitable? Please enlighten me.
getchar() needs to be able to indicate when it's reached the end of the input. It does this by returning EOF, which is deliberately outside the valid char range so it can't clash with a character appearing on the input.
The getchar function is returning an int because it need a way to signal an error while trying to read from the file. As the char type is only required to hold all possible value of characters, you need a larger type to be able to return EOF value.
This is so that when getchar() returns EOF, you can distinguish EOF from a real, valid char.