getc() != EOF

Andrew Koenig ark at rabbit.UUCP
Thu May 31 04:39:46 AEST 1984


>>> 
>>> In all conscience,
>>> 
>>> 	while ( (c = getc()) != EOF )
>>> 
>>> ought to work.  If somebody is to be blamed, it is surely not the
>>> people who wrote the code, but the people who made a C implementation
>>> that broke it.
>> 
>> It will work if "c" is declared "int."
>> It will not work if "c" is declared "char."
>> 
>> Variable declarations are an essential part of the program, and should be
>> included in illustrative code fragments, so problems are not concealed.
>> 
>>                                  Ed Nather

> WRONG! The code above will work if c is int or char.
> Char variables are promoted to int in expressions (see C manual)
> and a char -1 is IDENTICAL with an int -1. Unsigned char c could be
> different (Any C implementors there? (kvm?)). 
> 
> Chris Maltby
> University of Sydney
> 
 
Ed Nather is right here: a char -1 is not identical to an int -1.
C isn't obligated to sign-extend characters when converting to ints,
although it is obligated to refrain from sign-extending unsigned
chars.  Getc (and getchar) return ints, not chars, and the result
returned is always non-negative (except EOF), even on those
machines that sign-extend characters.  If I write:

	char c;

	while ((c = getc (file)) != EOF) ...

I will lose on a machine that sign-extends chars as soon as I read
a char with all its bits turned on, but it will work OK if c is an
int.


			--Andrew Koenig



More information about the Comp.unix.wizards mailing list