null in D

Steven Schveighoffer schveiguy at yahoo.com
Tue Aug 19 07:13:17 PDT 2008


"bearophile" wrote
> This is the C FAQ:
> ftp://ftp.eskimo.com/u/s/scs/C-faq/faq.gz
> at the point 5.2: it says:
>
>>an argument being passed to a function is not necessarily recognizable as 
>>a pointer context, and the compiler may not be able to tell that an 
>>unadorned 0 "means" a null pointer.  To generate a null pointer in a 
>>function call context, an explicit cast may be required<
> (Later the FAQ also explains why).
>
> So essentially in C this is the right thing to call foo() that takes a 
> pointer to int (using 0 instead of NULL is the same):
> foo((int *)NULL);
>
> So in D is this better, like in C:
> foo((int *)null);
>
> Or is this always enough in D?
> foo(null);

I would expect this probably is a side effect of 1) that NULL is not part of 
the language, and 2) some C standard libraries define NULL as 0.  Some 
define NULL as (void*)0, which probably don't have this problem.

I expect in D that since null is a first-class keyword, and not some alias 
or definition, its usage is understood correctly by the compiler to always 
be a pointer or null reference.

That being said, overloaded functions which have 2 versions which take 
different reference types must be selected by using a cast.  For example:

foo(int *i) {...}
foo(char *c) {...}

foo(null); // which one to call?

-Steve 




More information about the Digitalmars-d-learn mailing list