(c == '\n') is 1 or 0

Mark A Terribile mat at mole-end.UUCP
Fri Dec 16 18:04:34 AEST 1988


> <I'd write your program scrap as:
> <        while ( (c = getchar) != EOF)
> <        {   if (c == '\n')
> <                chcnt++;
> <            chcnt++;
> <        }
 
> 	     .... (c == '\n') is *guaranteed* to evaluate to 1 or 0, and
> nothing else. Thus, this is guaranteed to work:
> 	int c;		/* c needs to be an int, not a char	*/
>  	while ( (c = getchar()) != EOF)
>  		chcnt += 1 + (c == '\n');


I too prefer some variation on the first form; I would put the unconditional
increment first.  But if you want to do it the second way, here's how:

	int	c;
	while( ( c = getchar() ) != EOF )
		chcnt += ( c == '\n' ) ? 2 : 1 ;

After all, that's what they gave us ?: for!  That zero and one are the
coincidental representations of true and false can only make things more
confusing if we use them as numeric values as well.
-- 

(This man's opinions are his own.)
>From mole-end				Mark Terribile



More information about the Comp.lang.c mailing list