Re: Does the null-pointer-constant occupy storage?
/dev/null wrote:
Consider the following program.
#include <stdio>
const int NULL = 0; // Recommended NULL definition according to The C+
+ Programming Language by Bjarne Stroustrup.
// function that changes NULL.
void foo( void )
{
int *p = const_cast<int32 *>(&NULL);
*p = 42;
}
// Print value of NULL.
void print_null( void )
{
std::cout << NULL;
}
int main( void )
{
foo();
print_null();
}
Is this a well-formed C++ program?
If so, what will it print?
It invokes undefined behavior since you're writing to a null pointer. A
null pointer is just a significator that a pointer doesn't point to
anything useful. Dereferencing it invokes undefined behavior and makes
your program broken.
You specify a null pointer by a null pointer constant, which is an
integral constant zero in a pointer context. So your definition of NULL
(a const int 0) does not automatically create a null pointer unless it
is used in a pointer context (i.e., it initializes a pointer variable).
It does so in your function foo (though you then dereference it and
invoke undefined behavior), but it doesn't in your print_null function,
so all that does is print an integral zero, and has nothing to do with
pointers.
If you want to print the value of a null pointer (not that that's
terribly useful), cast it to a void * first:
std::cout << static_cast<void *>(0) << std::endl;
This will print some implementation-specific representation of the value
of a null pointer value. It may or may not be all-bits zero.
--
Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis
It is fatal to enter any war without the will to win it.
-- Douglas MacArthur, 1880-1964
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]