Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Return type of getchar(), fgetc() and getc() in C
In C programming, the character input functions getchar(), fgetc(), and getc() all return an int value, not a char. This is crucial because they need to return both valid character values (0-255) and the special value EOF (-1) to indicate end-of-file or error conditions.
Syntax
int getchar(void); int fgetc(FILE *stream); int getc(FILE *stream);
Why int Return Type?
All three functions return int instead of char because −
-
EOF handling:
EOFis typically -1, which cannot fit in an unsignedcharrange (0-255) - Error detection: Distinguishes between actual character values and error conditions
- Portability: Works consistently across different character encodings
Example 1: getchar() Function
The getchar() function reads a character from standard input −
#include <stdio.h>
int main() {
int ch;
printf("Enter a character: ");
ch = getchar();
if (ch == EOF) {
printf("Error or EOF encountered<br>");
} else {
printf("Character entered: %c (ASCII: %d)<br>", ch, ch);
}
return 0;
}
Enter a character: A Character entered: A (ASCII: 65)
Example 2: fgetc() Function
The fgetc() function reads a character from a specified file stream −
#include <stdio.h>
int main() {
FILE *fp;
int ch;
/* Create and write to file */
fp = fopen("test.txt", "w");
if (fp != NULL) {
fprintf(fp, "Hello");
fclose(fp);
}
/* Read from file */
fp = fopen("test.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
printf("File contents: ");
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
printf("<br>");
fclose(fp);
return 0;
}
File contents: Hello
Example 3: getc() Function
The getc() function is similar to fgetc() but may be implemented as a macro for better performance −
#include <stdio.h>
int main() {
int ch;
printf("Enter a character: ");
ch = getc(stdin);
if (ch == EOF) {
printf("EOF or error detected<br>");
} else {
printf("You entered: %c<br>", ch);
printf("Return value (int): %d<br>", ch);
}
return 0;
}
Enter a character: Z You entered: Z Return value (int): 90
Key Differences
| Function | Input Source | Implementation | Performance |
|---|---|---|---|
getchar() |
stdin only | Function | Standard |
fgetc() |
Any file stream | Function | Standard |
getc() |
Any file stream | Usually macro | Potentially faster |
Conclusion
All three functions return int to handle both character values and EOF conditions. Always store their return values in int variables and check for EOF to ensure proper error handling and program reliability.
