Subject: Re: NULL return value checking
To: NetBSD Kernel Technical Discussion List <tech-kern@NetBSD.ORG>
From: Greg A. Woods <>
List: tech-kern
Date: 04/24/2002 03:40:45
[ On , April 23, 2002 at 14:10:18 (-0700), wrote: ]
> Subject: Re: NULL return value checking
> For instance, the GNU coding standards say:
> > Try to avoid assignments inside if-conditions. For example, don't
> > write this: 
> > 
> > if ((foo = (char *) malloc (sizeof *foo)) == 0)
> >   fatal ("virtual memory exhausted");
> > 
> > instead, write this: 
> > 
> > foo = (char *) malloc (sizeof *foo);
> > if (foo == 0)
> >   fatal ("virtual memory exhausted");
> (Sure, that's not _actually_ a check against NULL, but it's an
> explicit test separate from the assignment, with the same intent an
> effect as a check against "NULL".)

I don't think that's a fair example.  The point of that example is, as
explicitly stated in the opening sentence, to separate the assignment
and the conditional test into separate statements.  Only by co-incidence
do both the "wrong" and "right" expressions in this example test the
value against zero, and use `==' instead of `!'....

When I search explicitly for NULL in the GNU Coding Standards document I
don't find any occurances, nor is there anything said explicitly about
using or not using `!' to test an integer type for a non-zero value.

I do agree though that given the relatively terse style of the GNU
Coding Standards "Writing C" node (titled "Making The Best Use of C")
such an example is at least a strong hint to those following this
standard for the way it would have them write such tests.

Definitive works describing the C Language, such as K&R and Harbison &
Steele don't seem to have any qualms about using the implicit comparison
to zero in expressions for conditional statements, and indeed the latter
book makes explicit mention of the fact that they are a commonly used
shorthand notation (p.122).  K&R say "It's hard to generalize about
which form is better" (p.42, 2nd Ed.), and I have to agree with them
wholeheartedly!  :-)

Regardless of which coding standard one might choose to follow, I think
it's important to note that every good C programmer must learn to read C
code which uses the implicit comparison against zero in conditionals.

[ K&R don't even seem to mind mixing assignments and test expressions
for conditional statements, and nor do I!  :-) ]

								Greg A. Woods

+1 416 218-0098;  <>;  <>;  <>
Planix, Inc. <>; VE3TCP; Secrets of the Weird <>