Take a look at the code statement below which assigns NULL
to an integer pointer (n
):
using namespace std;int main() {// your code goes hereint* n = NULL;return 0;}
Executing the above code gives the NULL undeclared error
at main.cpp:5:12
.
This happens because NULL
is not a built-in constant in the C or C++ languages. In fact, in C++, it’s more or less obsolete, instead, just a plain is used. Depending on the context, the compiler will do the right thing.
Since NULL
is not a built-in constant, external libraries, headers, or certain definitions are required to be able to use it. Here are a few:
#include <stdio.h>
#include <stddef.h>
: Add this line to use the pre-defined NULL
constant.
#include <iostream>
: Add this line to use the pre-defined NULL
constant.
#define NULL 0
: Add this line to define the NULL
constant as an equivalent of .
Simply use a instead of NULL
. They are the same thing when it comes to pointers.
In newer C++ (C++11 and higher), use nullptr
.
Free Resources