More NULL questions

Chris Torek chris at mimsy.UUCP
Sat Oct 7 13:19:10 AEST 1989


In article <5950001 at hpldola.HP.COM> jg at hpldola.HP.COM (Joe Gilray) writes:
>1) what is the danger with using
>         struct thing *ptr;
>         if (ptr != NULL) ...
[vs]
>         if (ptr != (struct thing *)NULL) ...
>   ?

None.  NULL (typically defined as `0' or, in newer compilers, `(void *)0')
becomes a nil pointer when it is used in a comparison or assignment
context where a pointer is needed.  The comparison contexts that can
change `0' to a particular nil pointer are `==' and `!='.  Assignment
contexts are comprised of assignments, casts, and prototyped arguments
to functions.

>         my_func(a, NULL, b);
[vs]
>         my_func(a, (struct thing *)NULL, b);
>   when
>   a) you are using function prototypes?

If a prototype for my_func() is in scope at the point of the call, the
only danger is confusion on the part of the reader (note that all other
contexts listed above are `short range', i.e., you can simply `look
near' the `0' or `NULL' to see if it is being used in an assignment
context, but not so in this case).

>   b) you are NOT using function prototypes (like me)?

If no prototype is in scope, the uncast NULL expands to 0, 0L, or (void
*)0, all of which have different types than (struct thing *)0, and all
of which could have different representations as well.  In other words,
if it works at all, that is mere luck.  (Whether the luck is good or
ill is a question perhaps best left unanswered.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list