Why is NULL undeclared?

前端 未结 5 1341
死守一世寂寞
死守一世寂寞 2020-11-30 02:55

I have a problem with this struct contructor when I try to compile this code:

typedef struct Node
{
    Node( int data ) //
    {
        this->data = dat         


        
相关标签:
5条回答
  • 2020-11-30 03:16

    Don't use NULL, C++ allows you to use the unadorned 0 instead:

    previous = 0;
    next = 0;
    

    And, as at C++11, you generally shouldn't be using either NULL or 0 since it provides you with nullptr of type std::nullptr_t, which is better suited to the task.

    0 讨论(0)
  • 2020-11-30 03:23

    NULL isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef> or #include <stddef.h> should be sufficient.

    The definition of NULL is guaranteed to be available if you include cstddef or stddef.h. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.

    0 讨论(0)
  • 2020-11-30 03:28

    NULL is not a built-in constant in the C or C++ languages. In fact, in C++ it's more or less obsolete, just use a plain literal 0 instead, the compiler will do the right thing depending on the context.

    In newer C++ (C++11 and higher), use nullptr (as pointed out in a comment, thanks).

    Otherwise, add

    #include <stddef.h>

    to get the NULL definition.

    0 讨论(0)
  • 2020-11-30 03:34

    Do use NULL. It is just #defined as 0 anyway and it is very useful to semantically distinguish it from the integer 0.

    There are problems with using 0 (and hence NULL). For example:

    void f(int);
    void f(void*);
    
    f(0); // Ambiguous. Calls f(int).
    

    The next version of C++ (C++0x) includes nullptr to fix this.

    f(nullptr); // Calls f(void*).
    
    0 讨论(0)
  • 2020-11-30 03:34

    Are you including "stdlib.h" or "cstdlib" in this file? NULL is defined in stdlib.h/cstdlib

    #include <stdlib.h>
    

    or

    #include <cstdlib>  // This is preferrable for c++
    
    0 讨论(0)
提交回复
热议问题