I'm wondering what type Null is in C. This is probably a duplicate, but I kept getting information about void type on searches. Maybe a better way is can NULL be returned for any type function? For example:
int main(){
dosomething();
return NULL;
}
Does that work?
Per C 2011 7.19 3,
NULL
“expands to an implementation-defined null pointer constant” (when any of several headers have been included:<locale.h>
,<stddef.h>
,<stdio.h>
,<stdlib.h>
,<string.h>
,<time.h>
, or<wchar.h>
).Per 6.3.2.3 3, a null pointer constant is “[A]n integer constant expression with the value 0, or such an expression cast to a type void *.” Thus, the C implementation may define
NULL
as simply0
or as((void *) 0)
, for example. Note that the former is anint
, not a pointer, but it may be compared to pointers, as inif (p == NULL) …
.Generally,
NULL
is intended to be used for pointers, not forint
values.In most C implementations, converting
NULL
to an integer will yield zero. However, I do not see this guaranteed in the C standard. (E.g., I do not see a guarantee that(int) (void *) 0 == 0
.)Short answer: The type of
NULL
isvoid*
orint
,long
,unsigned
, ...Addition to @Eric Postpischil fine answer to point out more coding pitfalls.
The type of
NULL
has many possibilities given "integer constant". Potable code should not assume a particular type.NULL
is best used in pointer contexts.