Open In App

NULL undeclared error in C/C++ and how to resolve it

What is undeclared Error: When we use some constant in our program maybe they are built-in constant and may be created by a user according to the requirement. But when we use some constant, and they are not built-in and also not defined by a user in that condition, we get an undeclared error. Below is the code that shows the example of NULL undeclared Error: 




using namespace std;
 
// Driver Code
int main()
{
    // NULL declared
    int* num = NULL;
    return 0;
}

Time complexity: O(1)

Auxiliary Space: O(1)

The above code will show an error as “NULL undeclared Error”. The reason for the NULL undeclared error is “NULL” is not a built-in constant. Why do we need NULL? When we create some pointer in our program, they are used for storing addresses. But an uninitialized pointer variable is very dangerous so that we can assign them NULL which means they are not pointing to any memory location, so our program runs smoothly and securely. Now if NULL is not built-in constant, how we can overcome the NULL undeclared error. Below are some code which is used to remove the NULL undeclared Error:




using namespace std;
 
// Driver Code
int main()
{
    int* num = 0;
    return 0;
}

Time complexity: O(1)

Auxiliary Space: O(1)




#include <stddef.h>
 
// Driver Code
int main()
{
    int* num = NULL;
    return 0;
}

Time complexity: O(1)

Auxiliary Space: O(1)




#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    int* num = NULL;
    return 0;
}

Time complexity: O(1)

Auxiliary Space: O(1)




#define NULL 0
using namespace std;
 
// Driver Code
int main()
{
    int* num = NULL;
    return 0;
}

Time complexity: O(1)

Auxiliary Space: O(1)




#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    int* num = nullptr;
    return 0;
}

Time Complexity: O(1) // Declaration/Initialization takes constant time
Auxiliary Space: O(1)


Article Tags :