Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

null
undeclared
error
c
c++

# What is the NULL undeclared error in C/C++?

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Take a look at the code statement below which assigns NULL to an integer pointer (n):

using namespace std;int main() {  // your code goes here  int* 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 $0$ is used. Depending on the context, the compiler will do the right thing.

## Solution

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 $0$.

• Simply use a $0$ inst​ead of NULL. They are the same thing when it comes to pointers.

• In newer C++ (C++11 and higher), use nullptr.

RELATED TAGS

null
undeclared
error
c
c++