Re: using literal zero for NULL

On Mar 21, 2006, at 8:37 AM, Hubert Figuiere wrote:

Jon A. Cruz wrote:

Thanks. I am using c++ so I must use protptypes. I use -Wall also.
For C++, 0 is supposed to be preferred over NULL. For varargs, though, the compiler might not know your intent. I've seen places that state modern compliers treat NULL as exactly 0 (in which case static_cast<void*>(0) should do the trick), however you should probably check on a C++ newsgroup for details.

I did the following program in C++:

#include <stdio.h>
int main(int argc, char** argv)
        printf("NULL: %d\n", sizeof(NULL));
        printf("zero: %d\n", sizeof(0));

The output on amd64 is as follow:

zero: 4

Note that in C, I get the exact same result.

So there is no reason to prefer 0 over NULL for pointers.

There are actually many reasons, and depending on the compiler, you'll see different things.

In the case you have there, you don't actually use NULL or 0, so the compiler goes with what it feels like. Try this instead:

#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
    void* p1 = 0;
    memset( &p1, 0xcc, sizeof(p1) );
    p1 = 0; // try both with and without this line

    unsigned char* itr = reinterpret_cast<unsigned char*>(&p1);
    for ( size_t i = 0; i < sizeof(p1); i++ )
        printf("  %02x\n", itr[i] );

Comment out p1=0 and you should see a bunch of CCs. Put it back and you should see all 00s, not just half zeros.

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]