3

So I'm reading K&R book and I have a question regarding this code:

int c;
c = getchar();

Why do they use integer variable? Isn't the value that getchar() returns a character? So a char would be more suitable? Please enlighten me.

Dvole
  • 5,725
  • 10
  • 54
  • 87
  • 1
    The answer is in the K&R book itself, on the same page as the first occurrence of this code (page 16 in my copy). – schot Oct 12 '11 at 08:08

5 Answers5

5

getchar() needs to be able to indicate when it's reached the end of the input. It does this by returning EOF, which is deliberately outside the valid char range so it can't clash with a character appearing on the input.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • +1 this is very sensible. But take a look at [a great question of R..](http://stackoverflow.com/questions/3860943/can-sizeofint-ever-be-1-on-a-hosted-implementation). It seems `getc` *could* return `EOF` as a valid character (so `feof` must be tested). – cnicutar Oct 11 '11 at 16:36
3

The getchar function is returning an int because it need a way to signal an error while trying to read from the file. As the char type is only required to hold all possible value of characters, you need a larger type to be able to return EOF value.

Sylvain Defresne
  • 42,429
  • 12
  • 75
  • 85
1

This is so that when getchar() returns EOF, you can distinguish EOF from a real, valid char.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

getchar returns EOF (-1) when the input file is at eof.

jim mcnamara
  • 16,005
  • 2
  • 34
  • 51
0

take a look http://msdn.microsoft.com/en-us/library/5231d02a(VS.71).aspx

StephenZhu
  • 34
  • 3