Open In App

What is return type of getchar(), fgetc() and getc() ?

Last Updated : 07 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Return Type of getchar()

The return type of getchar() is int.

  • Returns the ASCII value of the character as an int.
  • If an error occurs or the end of the input is reached, returns the special constant EOF (End Of File).

Return Type of getc()

The return type of getc() is int.

  • Returns the ASCII value of the character as an int.
  • If it encounters the end of the file or an error, returns EOF (End Of File).

Return Type of fgetc()

The return type of fgetc() is int.

  • Returns the ASCII value of the character as an int.
  • If it encounters the end of the file or an error, returns EOF (End Of File).

Why the knowledge of return type matters?

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:

C
#include <stdio.h>

int main() {
    FILE *fptr = fopen("file.txt", "r");
    if (!fptr) {
        perror("File opening failed");
        return 1;
    }

  	// Using char to store data
    char ch;
  
  	// Print each character
    while ((ch = fgetc(fptr)) != EOF) {
        printf("%c", ch);
    }

    fclose(fptr);
    return 0;
}


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:

  • Incorrect Handling of EOF: If EOF is returned and stored in a char variable, it might not be recognized correctly because EOF is -1, which could be misinterpreted as a valid character in the range of char.
  • Infinite Loop: If EOF is misinterpreted, the condition (ch != EOF) might never evaluate to false, resulting in an infinite loop.

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.


Next Article

Similar Reads