What is the difference between NULL, '\0' and 0?

前端 未结 11 1286
無奈伤痛
無奈伤痛 2020-11-21 16:32

In C, there appear to be differences between various values of zero -- NULL, NUL and 0.

I know that the ASCII character

11条回答
  •  臣服心动
    2020-11-21 16:50

    What is the difference between NULL, ‘\0’ and 0

    "null character (NUL)" is easiest to rule out. '\0' is a character literal. In C, it is implemented as int, so, it's the same as 0, which is of INT_TYPE_SIZE. In C++, character literal is implemented as char, which is 1 byte. This is normally different from NULL or 0.

    Next, NULL is a pointer value that specifies that a variable does not point to any address space. Set aside the fact that it is usually implemented as zeros, it must be able to express the full address space of the architecture. Thus, on a 32-bit architecture NULL (likely) is 4-byte and on 64-bit architecture 8-byte. This is up to the implementation of C.

    Finally, the literal 0 is of type int, which is of size INT_TYPE_SIZE. The default value of INT_TYPE_SIZE could be different depending on architecture.

    Apple wrote:

    The 64-bit data model used by Mac OS X is known as "LP64". This is the common data model used by other 64-bit UNIX systems from Sun and SGI as well as 64-bit Linux. The LP64 data model defines the primitive types as follows:

    • ints are 32-bit
    • longs are 64-bit
    • long-longs are also 64-bit
    • pointers are 64-bit

    Wikipedia 64-bit:

    Microsoft's VC++ compiler uses the LLP64 model.

    64-bit data models
    Data model short int long  long long pointers Sample operating systems
    LLP64      16    32  32    64        64       Microsoft Win64 (X64/IA64)
    LP64       16    32  64    64        64       Most Unix and Unix-like systems (Solaris, Linux, etc.)
    ILP64      16    64  64    64        64       HAL
    SILP64     64    64  64    64        64       ?
    

    Edit: Added more on the character literal.

    #include 
    
    int main(void) {
        printf("%d", sizeof('\0'));
        return 0;
    }
    

    The above code returns 4 on gcc and 1 on g++.

提交回复
热议问题