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

In C, there is no special method for comparing NULL values. We can use if statements to check whether a variable is null or not. NULL is a macro that represents a null pointer constant, typically defined as (void*)0.

Syntax

if (pointer == NULL) {
    /* pointer is null */
}

if (pointer != NULL) {
    /* pointer is not null */
}

Example 1: Checking File Pointer for NULL

Here, we 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 −

#include <stdio.h>

int main() {
    /* try to open a file in read mode, which is not present */
    FILE *fp;
    fp = fopen("nonexistent.txt", "r");
    
    if(fp == NULL) {
        printf("File does not exist or cannot be opened\n");
    } else {
        printf("File opened successfully\n");
        fclose(fp);
    }
    
    return 0;
}
File does not exist or cannot be opened

Example 2: Checking Pointer Variable for NULL

In this example, we assign a pointer value to NULL and check its existence using an if statement. After assigning some value to the pointer, it becomes not null −

#include <stdio.h>

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

    if (ptr == NULL) {
        printf("The pointer is NULL\n");
    } else {
        printf("The pointer is not NULL\n");
    }

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

    if (ptr != NULL) {
        printf("After assignment, pointer is not NULL\n");
        printf("Pointer points to value: %d\n", *ptr);
    }

    return 0;
}
The pointer is NULL
After assignment, pointer is not NULL
Pointer points to value: 100

Key Points

  • Always check for NULL before dereferencing a pointer to avoid segmentation faults.
  • Functions like malloc(), fopen(), and others return NULL on failure.
  • Use == NULL or != NULL for explicit comparison, or simply !ptr for checking if null.

Conclusion

Checking for NULL pointers is essential in C programming to prevent runtime errors. Always validate pointer values before using them to ensure program stability and correct behavior.

Updated on: 2026-03-15T10:42:33+05:30

27K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements