What type is NULL?

2019-02-19 01:10发布

问题:

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?

回答1:

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 simply 0 or as ((void *) 0), for example. Note that the former is an int, not a pointer, but it may be compared to pointers, as in if (p == NULL) ….

Generally, NULL is intended to be used for pointers, not for int 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.)



回答2:

What type is NULL?

Short answer: The type of NULL is void* or int, long, unsigned, ...


Addition to @Eric Postpischil fine answer to point out more coding pitfalls.

(macro) NULL which expands to an implementation-defined null pointer constant. C11dr §7.19 3

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. §6.3.2.3 3

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.

// Poor code as NULL may not match the type of the specifier - undefined behavior
printf("%p\n", NULL); // poor
printf("%d\n", NULL); // poor

// Better
printf("%d\n", (int) NULL);

// Best.  NULL is best used in a pointer context, print as a pointer
printf("%p\n", (void *) NULL);


标签: c null