I am beginner in C programming language, recently I have studied about getchar
function, which will accept a character from the console or from a file, display it immediately while typing and we need to press Enter key for proceeding.
It returns the unsigned char
that they read. If end-of-file or an error is encountered getchar()
functions return EOF.
My question is that, When it returns unsigned char
, then why its returned value is stored in int
variable?
Please help me.
The reason it returns an int rather than a char is because it needs to be able to store any character plus the EOF indicator where the input stream is closed.
The getc() function obtains a character from the stream that is specified. It returns the character that was read in the form of an integer or EOF if an error occurs.
In C, return type of getchar(), fgetc() and getc() is int (not char).
Precisely because of that EOF-value. Because a char in a file may be any possible char value, including the null character that C-strings use for termination, getchar()
must use a larger integer type to add an EOF-value.
It simply happens to use int for that purpose, but it could use any type with at least 9 bit.
The return type is int to accommodate for the special value EOF.
EOF is a macro which expands to an integer constant expression with type int and an implementation dependent negative value but is very commonly -1.
Read this link: link
Here it is written that:
Do not convert the value returned by a character I/O function to char if that value will be compared to EOF. Once the return value of these functions has been converted to a char type, character values may be indistinguishable from EOF. Also, if sizeof(int) == sizeof(char), then the int used to capture the return value may be indistinguishable from EOF. See FIO35-C. Use feof() and ferror() to detect end-of-file and file errors when sizeof(int) == sizeof(char) for more details about when sizeof(int) == sizeof(char). See STR00-C. Represent characters using an appropriate type for more information on the proper use of character types.
This rule applies to the use of all character I/O functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With