Cryptic C

Carl Zeigler jcz at ncsu.UUCP
Tue Aug 13 10:58:45 AEST 1985


  Refering to:
> 
> Subject: Re:  Cryptic C code?
> Message-ID: <605 at brl-tgr.ARPA>
> 
> I think case 2 is certainly more readable, but as the book says, you
> need to learn to read things like case 3 since a lot of code is like
> that.  More usually one will see something like
> 	char *s;
> 	...
> 	while ( *s++ )
> 		...
> I personally prefer to distinguish between Boolean
> expressions (such as comparisons) and arithmetic expressions, using
> strictly Boolean expressions as conditions.  Thus:
> 	while ( *s++ != '\0' )
> 
> Tests for NULL pointers and flags often are written
> 	if ( p )
> 		...
> 	if ( flag & BIT )
> 		...
> rather than
> 	if ( p != NULL )
> 		...
> 	if ( (flag & BIT) != 0 )
> 		...
> (I prefer the latter.)  Get used to it..


      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.

One of the definitions of C is that control statements work on the
zero - nonzero values of their controlling expressions.  Adding an extra
 != 0  has no affect other than to make the file larger. ( This is
hardly boolean !)

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 a much larger issue than wether

if ( exp == 0 ) foo;

adds anything to the readibility of the code. 

Perhaps we are discussing two separate issues:

One: how easy is it to see the code:  A cursory
    reader may miss the subtlety of 'while( *s++ )'
    whereas 'while( *s++ != 0 )' is a redundancy that
    makes missing the point more difficult.

Two: how easy it is to understand the code:
    Questions like how easy is it to tell just exactly why
    while( *s++ ) is needed here in the first place?  and  What
    is the goal?  Can I agree with the authors' need to post-increment
    his way through s?    Why not a pre-increment?

This is the kind of issue I believe K&R were focusing attention to in
their book and why they advocated learning certain 'idioms'.   Just as in
some more complex languages, idioms can carry more semantic content than
is reflected in a first glance at the expression of the idiom itself.

John Carl Zeigler
SAS Institute Inc.
919 467 5322
mcnc!ncsu!jcz



More information about the Comp.lang.c mailing list