if (p), where p is a pointer (REAL portability)
Guy Harris
guy at sun.uucp
Mon Sep 16 09:12:11 AEST 1985
> A constant zero IS safely converted into a "null" pointer of the
> appropriate type. IT IS NOT THE CASE that a "null" pointer of an
> arbitrary type is converted to or represented by all zero bits.
> char *p;
> if (p) /* NOT PORTABLE */
>
Wrong. "if (p)" is simply shorthand for "if (p != 0)" (see, I got it right
this time :-)), so if
if (p)
isn't portable, then
if (p != 0)
isn't portable either. (And it *is* portable - see next paragraph of reply.)
> Moreover, saying that NULL must be defined as zero is putting the cart
> before the horse. NULL must be defined as an invalid (char *) pointer
> and if your machine architecture wants that to be 0x555555, then that
> is what NULL should be defined as. It is coincidental and NONPORTABLE
> that NULL is usually defined as 0.
> char *p;
> if (p != 0) /* NOT PORTABLE */
> if (p != NULL) /* PORTABLE */
Wrong, wrong, wrong, wrong, wrong, wrong, wrong, wrong*! Go read K&R again,
It *very explicitly says* that "0", when it is used in an expression where a
pointer is expected (or generated, such as (char *)0), is converted to a
null pointer of the appropriate type. If the bit pattern for such a pointer
happens to be 0x555555, then
if (p != 0)
gets compiled as code to compare the bit pattern of "p" with the bit pattern
0x555555, regardless of the fact that a "0" happens to appear in the code.
> NULL is defined as "(char *)0", not as "0" on any sensible system
OK, you've just declared most UNIX implementations not to be sensible. NULL
is defined a "(char *)0" on systems which haven't implemented C correctly.
(See my response to Marty Shannon for an explanation of why declaring NULL
as anything other than 0 is incorrect.)
> ...even trivial compilers will generate identical code for
> if(p) /* BAD */
> if(p != (anytype *)0) /* GOOD */
ALL C COMPILERS GENERATE IDENTICAL CODE FOR THOSE TWO CASES. Anything that
does *not* generate identical code for them - even if that means comparing
the bits stored in "p" with the bit pattern of 0x555555 - is not a C
compiler. It is a compiler for a language which resembles C in some ways
but isn't C.
Moral: novice C programmers who ask questions in net.lang.c are probably
better off asking somewhere else. The chances are very good that the answer
they get will be totally wrong. Go out and buy a copy of Harbison and
Steele's "C: A Reference Manual" instead - despite the title, it's not just
a dry reference text, but contains a fair bit of useful tutorial information
(explaining things like null pointers, the proper use of "short", and all
sorts of topics which seem to be ill-understood by a depressingly large
segment of the C programming community and of the readership *and*
writership of this newsgroup).
Guy Harris
More information about the Comp.lang.c
mailing list