K
Keith Thompson
DevarajA said:Another thing.. looking into stddef.h I've seen that for C, NULL it is
defined as ((void*)0). The standard specifies that plain 0 is already
a null pointer constant. So why that cast? Maybe this is the last
stupid question for today
No, looking into the stddef.h header for your implementation tells you
how your implementation defines NULL. Another implementation could
define it as 0.
The standard says that a null pointer constant is "An integer constant
expression with the value 0, or such an expression cast to type void *",
and that NULL is a macro that "expands to an implementation-defined
null pointer constant".
One advantage of defining NULL as ((void*)0) rather than as 0 is that
it can catch some errors. A constant 0, though it's a null pointer
constant, can also be used in a non-pointer context; ((void*)0)
cannot. For example, I've seen code that incorrectly uses NULL to
denote a null character:
char s[50];
s[0] = NULL;
If NULL is defined as 0, this won't be diagnosed. If it's defined as
((void*)0), it will be.
Please ignore the remainder of this message.
There's actually some doubt about whether ((void*)0) is a legal
definition for NULL. The standard says that a constant 0 cast to
void* is a null pointer constant. It doesn't say that a constant 0
cast to void* *and enclosed in parentheses* is a null pointer
constant. C99 6.5.1 says a parenthesized expression "is an lvalue, a
function designator, or a void expression if the unparenthesized
expression is, respectively, an lvalue, a function designator, or a
void expression"; it doesn't say that a parenthesized expression is a
null pointer constant if the unparenthesized expression is a null
pointer constant.
This is nothing more than a minor glitch in the wording of the
standard, of no real significance either to programmers or to
implementers.