Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

c - What type is NULL?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...