Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about getchar function in C

Tags:

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!

like image 397
venkysmarty Avatar asked Feb 22 '26 09:02

venkysmarty


2 Answers

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)

like image 50
MByD Avatar answered Feb 23 '26 23:02

MByD


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.

like image 40
cnicutar Avatar answered Feb 24 '26 00:02

cnicutar