getc() != EOF
Morris Keesan
keesan at bbncca.ARPA
Mon Jun 4 22:50:07 AEST 1984
----------------------------
> > > while ( (c = getc()) != EOF )
> >
> > It will work if "c" is declared "int."
> > It will not work if "c" is declared "char."
> >
> > 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
1) When saying things like "See C manual", it would sure help if people would
give references -- preferably section numbers or page numbers.
2) The reference missing above is section 6.6, "Arithmetic conversions", on
page 184 of Kernighan and Ritchie:
A GREAT MANY operators cause conversions . . . called the "usual
arithmetic conversions."
First, any operands of type char . . . are converted to int.
(Emphasis mine -- there are some expressions where the usual arithmetic
conversions don't apply; above, they apply to !=, but NOT to = ).
3) From section 6.1 of the C manual (page 183 of K&R):
Whether or not sign-extension occurs for characters is machine
dependent . . . Of the machines treated by this manual, only the
PDP-11 sign-extends.
On many machines, char and unsigned char are equivalent. On these
machines, (char)-1 and (int)-1 are very different. C provides no
way to specify 'signed char' (a shortcoming of the language).
4) Even on machines that sign-extend characters, the above code is incorrect
if c is declared "char", because it will halt not only on EOF, but also on
(char)-1, which is a valid char.
--
Morris M. Keesan
{decvax,linus,wjh12,ima}!bbncca!keesan
keesan @ BBN-UNIX.ARPA
More information about the Comp.unix.wizards
mailing list