Re: union and overstamping zero values
andrew_nuss@yahoo.com <andrew_nuss@yahoo.com> wrote:
Not portably. The NULL pointer need not to be represented
by a bit pattern that also represents the zero integer
If so, then why does this work?:
main {
void* p = 0;
if (p == 0)
p = malloc(2000);
if (p)
free(p);
}
Because the NULL pointer is written as 0. It is the matter of the
compiler to figure out that this specific 0 is a NULL pointer constant
and not the all-zero bit pattern. Or rather, and to be more precise,
every numerical constant that evaluates to zero can be promoted to a
pointer, and is then the NULL pointer. This conversion is trivial on
platforms where the NULL pointer has the all-zero bit pattern, but not
all platforms are like that.
E.g.:
void *p = !!!!0;
is equivalent to the above, and no cast is required.
Similar, the implicit conversion from pointer to bool tests against the NULL
pointer and not against the zero-bit pattern.
I have chosen to use zero with pointers rather than the #define NULL
according to some recommendation that I saw once upon a time.
This is because some (old) platforms choose to define NULL as
#define NULL (void *)0
but this will cause trouble in C++ because there is no implicit
conversion from void * to any other pointer, unlike in C.
Some compilers offer a specific _null built-in key-word that allows
the compiler to check whether that NULL is erratically assigned to
a numerical (non-pointer) variable, it might be thus still a good
idea to use NULL, and just avoid broken compilers. But all that IMHO.
So long,
Thomas
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]