Cryptic C code?
VLD/VMB
gwyn at BRL.ARPA
Sun Aug 11 17:06:30 AEST 1985
First, the (char) in the while(expression) is NOT converted to an (int)
in case 3; it is tested against zero directly. In case 2 it is
converted to (int) for the comparison against '\0'.
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++ )
...
This really is a standard C idiom, although I don't recommend writing
code that way. I personally prefer to distinguish between Boolean
expressions (such as comparisons) and arithmetic expressions, using
strictly Boolean expressions as conditions. Thus:
while ( *s++ != '\0' )
or even
while ( (int)*s++ != '\0' )
The typecast is perhaps overly fussy; it is not required by the
language rules and may detract from readability.
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..
More information about the Comp.lang.c
mailing list