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

CC++Server Side ProgrammingProgramming

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");
   fclose(fp);
}

Output

File does not exists
raja
Published on 28-May-2019 16:12:33
Advertisements