/

How to Use NULL in C: A Guide for Programmers

How to Use NULL in C: A Guide for Programmers

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:

1
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:

1
2
3
4
5
#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:

1
2
3
4
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:

1
2
3
4
5
6
7
8
9
#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:

1
char *a_string = '\0';

Tags: C programming, null pointers, pointers in C