What type is NULL?

c, null

Solution

The type of `NULL` may be either an integer type or `void *`. This is because the C standard allows it to be defined as either an integer constant expression or the result of a cast to `void *`.

C 2018 7.19 3 says `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>`).

C 6.3.2.3 3 says a null pointer constant is “An integer constant expression with the value 0, or such an expression cast to a type `void *`.”

Thus, a C implementation may define `NULL` as, for example:

- `0`, which has type `int`,

- `((void *) 0)`, which has type `void *`, or

- `(1+5-6)`, which is an integer constant expression with value 0 and type `int`.

Even though `NULL` may have an integer type, it may be compared to and assigned to pointers, as in `if (p == NULL) …`. The rules for these operations say that an integer constant zero will be converted to the appropriate pointer type for the operation.

Although `NULL` may be defined to be `0`, it is intended to be used for pointers, not as an integer zero. Programs should avoid doing that, and C implementations are generally better off defining it as `((void *) 0)` to help avoid mistakes where it might be accepted as an integer value.

In most C implementations, converting `NULL` to an integer will yield zero. However, this is not guaranteed in the C standard. It is allowed that `(int) NULL` or `(uintptr_t) NULL` will produce the address of some special “do not use” location rather than zero. Even `(int) (void *) 0` might produce such an address rather than zero.

When an integer constant zero is converted to a pointer type, it is treated specially by the C implementation; it produces a null pointer for that implementation even if its null pointer uses an address other than zero. The fact that it is an integer constant means the compiler can apply this special treatment where it recognizes the conversion in the source code. If we have some non-constant expression, such as an `int` variable `x`, then `(void *) x` is not guaranteed to yield a null pointer even if the value of `x` is zero.

Problem

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?

Original source