Why doesn't this work? (3B2 problem)

Steve Schlaifer x3171 156/224 steve at jplgodo.UUCP
Sat Mar 22 03:55:32 AEST 1986


In article <276 at birtch.UUCP>, ken at birtch.UUCP (Ken B) writes:
> We have a 3B2/300, and I wrote this program to help debug our spooler problem
> (another story), why doesn't it work?  It never read's an EOF from stdin,
> and continues to dump 'nulls' to stdout.  
..................code deleted..........................
> 	char c;
> 
> 	c=getchar();
> 	if (c!=EOF)
............... remaining code deleted .................
> 
> This exact program works correctly on our Pyramid 90x, so I know its not just
> my program.

The getchar function is of type int; EOF is defined in stdio to have the value
-1.  When you say c=getchar(); and encounter an end of file, the value -1 from
getchar is converted to \377 when it is stored in c.  When c is later compared
to EOF, the value of c is converted to int and then the comparison is done.
This is all true no matter which machine you are running on.

I suspect the 3B2 uses unsigned char's and the Pyramid uses signed char's.
When \377 is converted to int on the 3B2, it becomes +127; on the Pyramid, it
becomes -1.  Obviously, +127 is not equal to -1 so c can never be equal to EOF
on the 3B2.  On the Pyramid, the sign extension done when a char is converted
into an int makes everything work out fine.  An easy fix for this type of
problem is to declare c as an int rather than a char.

-- 

...smeagol\			Steve Schlaifer
......wlbr->!jplgodo!steve	Advance Projects Group, Jet Propulsion Labs
....group3/			4800 Oak Grove Drive, M/S 156/204
				Pasadena, California, 91109
					+1 818 354 3171



More information about the Comp.lang.c mailing list