Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
== NULLor!= NULLfor explicit comparison, or simply!ptrfor 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.
Advertisements
