Search code examples
ccharinteoffgetc

Clarification on the use of fgetc


There is the following code from part of a function that I have been given:

char ch;
ch = fgetc(fp);
if (ch == EOF)
  return -1;

Where fp is a pointer-to-FILE/stream passed as a parameter to the function.

However, having checked the usage of fgetc(),getc() and getchar(), it seems that they all return type int rather than type char because EOF does not fit in the values 0-255 that are used in a char, and so is usually < 0 (e.g. -1). However, this leads me to ask three questions:

  1. If getchar() returns int, why is char c; c = getchar(); a valid usage of the function? Does C automatically type cast to char in this case, and in the case that getchar() is replaced with getc(fp) or fgetc(fp)?
  2. What would happen in the program when fgetc() or the other two functions return EOF? Would it again try and cast to char like before but then fail? What gets stored in ch, if anything?
  3. If EOF is not actually a character, how is ch == EOF a valid comparison, since EOF cannot be represented by a char variable?

Solution

  • If getchar() returns int, why is char c; c = getchar(); a valid usage of the function?

    It's not. Just because you can write and compiler (somehow) allows you to compile it, does not make a code valid.

    I believe the above answers all the questions.

    Just to add, in case EOF is returned, it cannot be stored in a char. Signedness of a char is implementation defined, thus, as per chapter 6.3.1.3, C11

    1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

    2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.60)

    3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.