ProgrammingModerate

Why must the result of getchar() be stored in an int rather than a char?

  1. A. Because int is faster than char on all hardware
  2. B. Because EOF (-1) must be distinguishable from every byte value, and a char may be unsigned and unable to hold -1
  3. C. Because getchar returns a pointer to a char
  4. D. Because char cannot hold a newline character

Correct answer: B. Because EOF (-1) must be distinguishable from every byte value, and a char may be unsigned and unable to hold -1

getchar returns every unsigned char value as a non-negative int plus the negative EOF. A char that is unsigned cannot hold -1, so the loop test would never see end of file.

More C Programming questions

Exams that ask this topic