Table of Contents
Most programming languages have some concept of null values. Generally, null is a value that represents nothing and therefore is usually used to represent the absence of a value when a variable is not initialized.
For example, JavaScript uses null
, Python uses None
, and Ruby uses nil
.
C, uses NULL
.
While null
is usually used to represent the absence of a value, in C, it is used to represent a null pointer.
When you want to initialize a pointer but don't yet have a value, you can use NULL
.
CLIKEint *pointer = NULL;
To ensure that you don't get the use of undeclared identifier
error, make sure to include the stdio.h
header file that comes with C.
CLIKE#include <stdio.h>
int main() {
int *pointer = NULL;
printf("%p", pointer);
return 0;
}
In addition to using it as a value to set a new pointer to, you can also use NULL
to check if variables are pointing to a valid address or not.
Here's how to check if a pointer is a null pointer or not in C:
CLIKE#include <stdio.h>
int main() {
int *pointer = NULL;
if (pointer == NULL) {
printf("Pointer is NULL");
} else {
printf("Pointer is not NULL");
}
return 0;
}
BASHPointer is NULL
Under the hood, NULL
is just a constant pointer guaranteed to not point to any valid address.
In some cases, you could replace NULL
with 0
to get the same result, but the intent of your code will be more clear if you use NULL
instead.
Conclusion
Hopefully, this post gave you a quick overview of how NULL
works in C.
You can use NULL
to initialize a variable to point to nothing, or use it to check if a pointer is a null pointer or not.
Happy coding!
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Setting Up Stylus CSS Preprocessor