Cryptic C

Doug Gwyn <gwyn> gwyn at brl-tgr.ARPA
Thu Aug 15 18:33:05 AEST 1985


> > I personally prefer to distinguish between Boolean
> > expressions (such as comparisons) and arithmetic expressions, using
> > strictly Boolean expressions as conditions.  Thus:
> > 	while ( *s++ != '\0' )

>       While I certainly agree that code should be written
> so that it is readible, I do not see how the relational operators
> in the above examples really improve the readibility of the code.

Perhaps I can make this point clearer.  Nearly all Algol-like
languages have a separate Boolean data type, and their conditional
expressions are required to be of Boolean type.  In C, arithmetic
expressions are made to do double duty and are interpreted in
Boolean contexts as "true" if and only if the value is nonzero.
While this kludge obviously works, I think it adds one extra level
of mental processing when one is reading conditionals in C.  This
is because there is no visible percept corresponding to one's
thoughts about comparison against zero; one has to explicitly apply
a conceptual language evaluation rule to map the expression into a
condition in order to extract the full meaning of the condition.

Many Boolean expressions are not best thought of as comparison of
an arithmetic quantity against zero.  For example:
	while ( ! Done() )
		Perform_Action();
I have found that introducing Booleans as an explicit data type
into my C code has helped me produce better-organized code having
clearer meaning (once you get used to the idea).  Although these
days I am pretty conservative when it comes to defining one's own
language extensions, this one seems like a winner:

	typedef int	bool;
	#define	false	0
	#define	true	1

And of course I can still read idiomatic C code produced by others,
but I do notice the extra effort required.

> Readible code is code where the authors intent is clear, where
> the data structures and the types of operations that can be
> performed on the data structures make sense in the context of the
> problem being solved.

This is an excellent point.  Perhaps I shouldn't be taking that
for granted.



More information about the Comp.lang.c mailing list