venkysmarty
venkysmarty

Reputation: 11431

about getchar function in C

I am reading K & R C language book, following code fragment:

char c;
while ((c = getchar()) != EOF) ...

It was mentioned that for EOF (i think it is -1) is an "out of band" return value from getchar, distinct from all possible values that getchar can return.

My questions are following:

  1. I ran my program with char and it ran successfully, and my understanding is signed char can store -127 to +127 so it can check for -1 how it is "out of band" ?
  2. Can any one provide simple example where above program fragment will fail if we use char c instead of int c?

Thanks!

Upvotes: 3

Views: 1068

Answers (3)

Hyperboreus
Hyperboreus

Reputation: 32429

Whatever value EOF has depends on your platform. Take a look at stdio.h too see its actual definition.

Upvotes: 2

cnicutar
cnicutar

Reputation: 182619

Well, your question is answered in the C FAQ.

Two failure modes are possible if, as in the fragment above, getchar's return value is assigned to a char.

  • If type char is signed, and if EOF is defined (as is usual) as -1, the character with the decimal value 255 ('\377' or '\xff' in C) will be sign-extended and will compare equal to EOF, prematurely
    terminating the input.

  • If type char is unsigned, an actual EOF value will be truncated (by having its higher-order bits discarded, probably resulting in 255 or 0xff) and will not be recognized as EOF, resulting in effectively infinite input.

Upvotes: 5

MByD
MByD

Reputation: 137282

You have a small mistake, getchar returns an int, not a char:

int c;
while ((c = getchar()) != EOF) ...

The valid values for ascii chars are from 0 to 127, the EOF is some other (int) value.

If you keep using char, you might get into troubles (as I got into)

Upvotes: 6

Related Questions