16

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.

phuclv
  • 32,499
  • 12
  • 130
  • 417
Mayank Tiwari
  • 2,861
  • 5
  • 27
  • 48
  • 5
    A good link: [Definition of EOF and how to use it effectively](http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?id=1043284351&answer=1048865140) – Grijesh Chauhan Aug 02 '13 at 09:25
  • See also [`while ((c = getc(file)) != EOF)` loop won't stop executing](https://stackoverflow.com/questions/13694394/while-c-getcfile-eof-loop-wont-stop-executing/). – Jonathan Leffler Feb 12 '17 at 03:16
  • 2
    Possible duplicate of [Difference between int and char in getchar/fgetc and putchar/fputc?](http://stackoverflow.com/questions/35356322/difference-between-int-and-char-in-getchar-fgetc-and-putchar-fputc) – Antti Haapala -- Слава Україні May 19 '17 at 10:06

3 Answers3

19

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.

cmaster - reinstate monica
  • 36,366
  • 8
  • 54
  • 104
  • 1
    Detail: "a char in a file may be any possible char value" --> a character may have many a possible value, but the value returned from `getchar()` is a character's `unsigned char` value, not its `char` value. – chux - Reinstate Monica Apr 12 '17 at 04:39
4

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.

Dayal rai
  • 6,308
  • 21
  • 29
2

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.

jfs
  • 374,366
  • 172
  • 933
  • 1,594
Mayank Tiwari
  • 2,861
  • 5
  • 27
  • 48