Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must the variable used to hold getchar's return value be declared as int?

Tags:

c

function

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.

like image 969
Mayank Tiwari Avatar asked Aug 02 '13 09:08

Mayank Tiwari


People also ask

Why does Getchar return an int instead of a char?

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.

What does GETC return in C?

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.

What is the default return type of getchar ()?

In C, return type of getchar(), fgetc() and getc() is int (not char).


3 Answers

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.

like image 131
cmaster - reinstate monica Avatar answered Oct 10 '22 09:10

cmaster - reinstate monica


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.

like image 42
Dayal rai Avatar answered Oct 10 '22 11:10

Dayal rai


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.

like image 26
Mayank Tiwari Avatar answered Oct 10 '22 09:10

Mayank Tiwari