How to check if a variable is NULL in C/C++?



In C/C++, there is no special method for comparing NULL values. We can use if statements to check whether a variable is null or not.

Here, we will attempt to open a file in read mode that does not exist on the system. In this case, the function will return a NULL pointer. We can check whether it is NULL or not using an if statement.

C Example to Check Variable is NULL or Not

In this example, we check whether the file is exist or not using NULL.

#include<stdio.h>
int main() {
   //try to open a file in read mode, which is not present
   FILE *fp;
   fp = fopen("hello.txt", "r");
   if(fp == NULL)
      printf("File does not exists");
   fclose(fp);
   return 0;
}

C++ Example to Check Variable is NULL or Not

In this example, we assign the pointer value to NULL and check the existence of NULL using if statement. After passing some value to pointer, it becomes not null and generate that value as result.

#include<iostream>
using namespace std;

int main() {
   // Pointer initialized to NULL
   int* ptr = NULL;  

   if (ptr == NULL) {
       cout << "The pointer is NULL." << endl;
   } else {
       cout << "The pointer is not NULL." << endl;
   }

   // Assign some value
   int value = 100;
   ptr = &value;

   if (ptr != NULL) {
       cout << "After assignment, pointer is not NULL." <<  endl;
       cout <<  "Pointer points to value: " <<  *ptr <<  endl;
   }

   return 0;
}

The above program produces the following result:

The pointer is NULL.
After assignment, pointer is not NULL.
Pointer points to value: 100
Updated on: 2025-06-11T14:20:52+05:30

26K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements