if (p), where p is a pointer - PLEASE READ
Guy Harris
guy at sun.uucp
Thu Sep 12 19:06:22 AEST 1985
> An C idiom I see (and write) frequently is
>
> if (ptr)
>
> Will this work correctly on a machine where NULL is not 0? Does it really
> need to say
>
> if (ptr != NULL)
1) "if (X)" means exactly the same thing as "if (X == 0)", for all X
(assuming "if (X == 0)" has a meaning in the first place, i.e. if X is a
struct, forget it).
2) NULL is #defined to be 0, so "if (ptr == NULL)" is equivalent to "if (ptr
== 0)".
So both statements are equivalent. The compiler is capable of realizing
that the LHS of the comparison is a pointer and the RHS is the constant 0,
and generates code to compare the pointer to a null pointer of the
appropriate type. The only place where the compiler can't recognize that a
constant 0 is really a null pointer of the appropriate type is in a function
call (i.e., "setbuf(stream, 0)" and "setbuf(stream, NULL)" are wrong; you
have to say "setbuf(stream, (char *)0)" or "setbuf(stream, (char *)NULL)").
ANSI C will permit you to say something like
void setbuf(FILE *, char *);
in <stdio.h>, in which case the compiler knows that the "0" in "setbuf(0)"
is to be converted to "(char *)0" and will do it for you.
Guy Harris
More information about the Comp.lang.c
mailing list