LWN.net Logo

NULL v. zero

NULL v. zero

Posted Jul 15, 2004 19:37 UTC (Thu) by Ross (subscriber, #4065)
In reply to: NULL v. zero by ikm
Parent article: NULL v. zero

Actually, no. C++ is a little more strict. C++ doesn't have a generic
pointer type like C.

Valid C:

int *ptr=malloc(10*sizeof(int));

That's not valid C++. Instead you have to do this:

int *ptr=(int *)malloc(10*sizeof(int));

Which is really annoying because it is obvious from the context what the
type should be, and it masks the bug of not including stdlib.h before
calling malloc.

So in C++ the nil pointer is 0 (they are very adamant about this).
In C it is NULL, which can be either (void *)0 or 0. The first is
obviously better since the compiler will complain if it is used in
invalid contexts but it's a quality of implementation issue not a
conformance issue.


(Log in to post comments)

NULL v. zero

Posted Jul 15, 2004 20:20 UTC (Thu) by dvdeug (subscriber, #10998) [Link]

Actually, C++ won't compile if you don't have a function prototype for malloc in scope. If you don't include <stdlib.h> or something else that includes a malloc function, it simply won't work.

NULL v. zero

Posted Jul 15, 2004 23:52 UTC (Thu) by dododge (subscriber, #2870) [Link]

The header inclusion issue is in C, not C++. The differences in the languages mean that there is no single way to call malloc that works well for both of them.

If you're writing C++ you have to cast malloc because the compiler won't like the implicit conversion. If you're writing C you shouldn't cast it, in order to force the compiler to warn you if there's no prototype in scope.

Where you can run into trouble is when you've got code or a programmer moving betwen the two languages.

Copyright © 2008, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds