error: ‘NULL’ was not declared in this scope

C++GccPointersNull

C++ Problem Overview


I get this message when compiling C++ on gcc 4.3

error: ‘NULL’ was not declared in this scope

It appears and disappears and I don't know why. Why?

Thanks.

C++ Solutions


Solution 1 - C++

NULL is not a keyword. It's an identifier defined in some standard headers. You can include

#include <cstddef>

To have it in scope, including some other basics, like std::size_t.

Solution 2 - C++

GCC is taking steps towards C++11, which is probably why you now need to include cstddef in order to use the NULL constant. The preferred way in C++11 is to use the new nullptr keyword, which is implemented in GCC since version 4.6. nullptr is not implicitly convertible to integral types, so it can be used to disambiguate a call to a function which has been overloaded for both pointer and integral types:

void f(int x);
void f(void * ptr);

f(0);  // Passes int 0.
f(nullptr);  // Passes void * 0.

Solution 3 - C++

NULL isn't a keyword; it's a macro substitution for 0, and comes in stddef.h or cstddef, I believe. You haven't #included an appropriate header file, so g++ sees NULL as a regular variable name, and you haven't declared it.

Solution 4 - C++

To complete the other answers: If you are using C++11, use nullptr, which is a keyword that means a void pointer pointing to null. (instead of NULL, which is not a pointer type)

Solution 5 - C++

NULL can also be found in:

#include <string.h>

String.h will pull in the NULL from somewhere else.

Solution 6 - C++

You can declare the macro NULL. Add that after your #includes:

#define NULL 0

or

#ifndef NULL
#define NULL 0
#endif

No ";" at the end of the instructions...

Solution 7 - C++

If you look carefully into NULL macro in any std header:

> #define NULL __null

So basically, you may use the __null keyword instead.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjackhabView Question on Stackoverflow
Solution 1 - C++Johannes Schaub - litbView Answer on Stackoverflow
Solution 2 - C++Seppo EnarviView Answer on Stackoverflow
Solution 3 - C++David ThornleyView Answer on Stackoverflow
Solution 4 - C++Leonardo RaeleView Answer on Stackoverflow
Solution 5 - C++OwlView Answer on Stackoverflow
Solution 6 - C++DerzuView Answer on Stackoverflow
Solution 7 - C++Vedant PanchalView Answer on Stackoverflow