In many programming languages, including Go, JavaScript, and Python, the concept of null is widely used. Similarly, C has its own representation called NULL. However, it is important to note that the usage of NULL in C is different compared to other languages. In C, NULL is specifically used to represent a null pointer.
When working with pointers in C, there are situations where we might not know what the pointer points to during initialization. This is where NULL comes in handy:
int *p_some_variable = NULL;
Please remember that NULL is not available by default in C. To use it, you need to include the header file stdio.h (or alternatively, stddef.h). Here’s an example:
#include <stdio.h>
int main(void) {
int *p_some_variable = NULL;
}
If you attempt to use NULL without including the necessary header file, the C compiler will throw an error, as shown below:
hello.c:3:26: error: use of undeclared identifier 'NULL'
int *p_some_variable = NULL;
^
1 error generated.
To check whether a pointer is a null pointer, you can compare it to NULL. Here’s an example:
#include <stdio.h>
int main(void) {
int *p_some_variable = NULL;
if (p_some_variable == NULL) {
printf("Equal");
}
}
In practice, NULL is a constant that is equivalent to 0 or "\0". This is why you can assign NULL to a string using the following syntax:
char *a_string = '\0';
Tags: C programming, null pointers, pointers in C