Re: correct way to initialize pointer...

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

 




On Tue, 24 Oct 2006, Mandeep Sandhu wrote:

I read some time ago (can't remember where!), that 0 is not always
an invalid address. Though I think the C compiler is supposed to generate
one for any such assignments (as shown above). Is this a C standard?
Are all compilers supposed to do it?
Shouldn't NULL be a better choice so that we can #define it to an invalid
value, where this #define is specific to an architechture?? CMIIW.

This is a confusing issue which crops up now and then. There's a very lucid explanation of 0 vs. NULL vs. illegal values in the C FAQ, see for instance http://c-faq.com/null/index.html .

In short, when a compiler sees a 0 in a pointer context, it converts into the internal representation for a null pointer for the architecture in question. It doesn't matter if it's used in assigment ( p = 0 ) or as part of an expression ( if (p == 0) ), or even implicitly in an expression ( if (!p) ).

It is also true that most processors actually use the value 0 for the null pointer.

Semantically NULL is identical to 0, so if you write p = 0 or p = NULL there is absolutely no difference as far as the compiler is concerned. NULL is usually #defined to 0, and 0 will cause the compiler to create a null pointer in a pointer context. In many cases NULL is #defined to (void *) 0 in order to catch type conversion bugs.

At any rate, many people feel that NULL is better than 0 when used with pointers as it indicates that the expression is a pointer type. But it makes no difference to the compiler or to the resulting code.

/Ricard
--
Ricard Wolf Wanderlöf                           ricardw(at)axis.com
Axis Communications AB, Lund, Sweden            www.axis.com
Phone +46 46 272 2016                           Fax +46 46 13 61 30

--
Kernelnewbies: Help each other learn about the Linux kernel.
Archive:       http://mail.nl.linux.org/kernelnewbies/
FAQ:           http://kernelnewbies.org/faq/



[Index of Archives]     [Newbies FAQ]     [Linux Kernel Mentors]     [Linux Kernel Development]     [IETF Annouce]     [Git]     [Networking]     [Security]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux SCSI]     [Linux ACPI]
  Powered by Linux