Simple C Question (was: down)

Andrew Koenig ark at alice.UUCP
Tue Dec 20 00:48:14 AEST 1988


In article <6959 at pyr.gatech.EDU>, byron at pyr.gatech.EDU (Byron A Jeff) writes:

> I think I like one of the following two better:
> chcnt += (c == '\n') ? 2 : 1;
> chcnt += 1 + (c == '\n');
 
> Any comments one which one of the ones we've seen is most efficient?

If the problem is stated this way:

	count all the characters and count one extra for each newline

then it seems to me that the most direct solution is:

	chcnt++;
	if (c == '\n')
		chcnt++;

I suspect this is also the fastest on most machines.  For example,
here are instruction counts for the compiler on my machine:

	c=='\n'		c!='\n'		statement

	6		6		chcnt += (c == '\n') ? 2 : 1;
	5		4		chcnt += 1 + (c == '\n');
	4		3		chcnt++;
					if (c == '\n')
						chcnt++;

This assumes that c and chcnt are both in registers.
-- 
				--Andrew Koenig
				  ark at europa.att.com



More information about the Comp.lang.c mailing list