I’ve been playing around with C23’s new features and I came across nullptr
, and I’d like to use it in place of NULL
where possible, or at least in demo code to better understand proper usage.
Here is an example of some code where I tried to replace NULL
with nullptr
, as you might do in C++:
#include <stdio.h>
#include <stddef.h>
int main() {
int x = 10;
int* ptr = &x;
if(ptr != nullptr) {
printf("ptr not null!");
}
}
I’m using gcc 13.2.0, which should support C23’s nullptr. Surprisingly, compilation fails with or without the -std=c2x
flag.
Here is the error gcc gives:
nullptr.c: In function 'main':
nullptr.c:7:15: error: 'nullptr' undeclared (first use in this function); did you mean 'nullptr_t'?
7 | if(ptr != nullptr) {
| ^~~~~~~
| nullptr_t
nullptr.c:7:15: note: each undeclared identifier is reported only once for each function it appears in
Replacing nullptr
with the type nullptr_t
doesn’t make sense, it’s looking for an expression before a type name like nullptr_t
, and indeed that is what happens.
I can get a successful compilation and expected behavior with simple casting NULL
to nullptr_t
:
if(ptr != (nullptr_t)NULL)
My assumption is that this is not the proper or intended usage of C23’s nullptr
, and there’s something I’m missing.
jitters is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.