![]() |
VOOZH | about |
In C, getchar(), fgetc(), and getc() all are the functions used for reading characters from input buffer. This buffer is standard input buffer for getchar() and can be any specified file for getc() and fgetc(). In this article, we will learn about the return type of these functions and why it matters in C.
The return type of getchar() is int.
The return type of getc() is int.
The return type of fgetc() is int.
As all these functions reads a single character, it is often assumed by the programmers that the return type of these functions must be of char type. But these functions either return the ASCII value or EOF which is typically defined as -1 is most implementations.
So, the return value of these functions is assigned to char (which can be an unsigned short int in some platforms), the EOF value may get converted into 2's complement leading to undefined error or infinite loop.
The below example demonstrates how it can happen:
The above program may run well in most of the platforms, where char is signed short int. But in others, it may lead to following problems:
That is why, it is recommended to store the value returned by these functions into an int variable and treat it as char or typecast it after verification.