Why is NULL undeclared?

TheTeh picture TheTeh · May 29, 2009 · Viewed 190.8k times · Source

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

typedef struct Node
{
    Node( int data ) //
    {
        this->data = data;
        previous = NULL; // Compiler indicates here
        next = NULL;
    }

    int data;
    Node* previous;
    Node* next;
} NODE;

when I come this error occurs:

\linkedlist\linkedlist.h||In constructor `Node::Node(int)':|
\linkedlist\linkedlist.h|9|error: `NULL' was not declared in this scope|
    ||=== Build finished: 1 errors, 0 warnings ===|

Last problem was the struct, but it worked fine when it was in my main.cpp, this time it's in a header file and is giving me this problem. I am using Code::Blocks to compile this code

Answer

unwind picture unwind · May 29, 2009

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.