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 |
|
If you attempt to use NULL
without including the necessary header file, the C compiler will throw an error, as shown below:
1 | hello.c:3:26: error: use of undeclared identifier 'NULL' |
To check whether a pointer is a null pointer, you can compare it to NULL
. Here’s an example:
1 |
|
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