C programming style poll

Philip Lantz philipl at azure.UUCP
Fri Apr 27 21:04:41 AEST 1984


>From a style point of view, I personally prefer

	y = (x == 5);

WITH the parentheses, but NOT without them.  I think Boolean expressions
are as valid a part of the C language as they are of Pascal, even though
there is no specific declaration for Boolean variables.

However, since I have a compulsion to write the tightest code possible,
I use
	y = 0;
	if (x == 5)
	    y = 1;
What's that?  Yes, on every C compiler I've checked (pcc and Ritchie
and others) the version with the "if" generates BETTER code than
either of the other two forms.  (The other two forms generate identical
code.)

By the way, I agree that the first form above may not be guaranteed to
be entirely equivalent to the others, but if y is assigned to a Boolean
expression, it should be tested with
	if (y)
	if (!y)
or possibly
	if (y == 0)
	if (y != 0)
but never with
	if (y == 1)
	if (y != 1)
The first four forms generate better code (no compare instruction on most
machines), but especially do not depend on the value of a Boolean being 1
when true.

Philip Lantz
Tektronix, Inc.
tektronix!tekmdp!philipl



More information about the Comp.lang.c mailing list