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

In C or 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 see one program. We will try to open a file in read mode, that is not present in the system. So the function will return null value. We can check it using if statement. See the code for better understanding.

Example Code

#include <stdio.h>
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");


File does not exists

Updated on: 30-Jul-2019

21K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started