What type is NULL?

后端 未结 2 1835
醉梦人生
醉梦人生 2020-12-10 18:13

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 f

相关标签:
2条回答
  • 2020-12-10 18:27

    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);
    
    0 讨论(0)
  • 2020-12-10 18:47

    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 “An 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, or something weirder like (1+5-6) (which is an integer constant expression with the value 0). 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.)

    0 讨论(0)
提交回复
热议问题