Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is _Nullable pointer in C?

Tags:

c

What does _Nullable mean in following declaration?

void foo(int *_Nullable ptr)

gcc of version 11.4 doesn't compile that code, because it treats _Nullable keyword as an argument name. Yet I see this keyword in man 7 pages: https://man7.org/linux/man-pages/man2/epoll_ctl.2.html https://man7.org/linux/man-pages/man2/timer_gettime.2.html

Godbolt

like image 583
Zhalgas Yerzhanov Avatar asked Sep 12 '25 17:09

Zhalgas Yerzhanov


2 Answers

_Nullable simply means that the pointer passed to the function is allowed to be NULL. It is however not a keyword in C (and doesn't occur even once in the draft for the C23 standard) but an extension supported only by some compilers, for example clang and icx.

The Linux man pages uses _Nullable to indicate to the readers that they are allowed to pass in a NULL pointer, but the actual declarations in the header files are free from _Nullable.


Libraries who wishes to give the compiler the static analysis and optimizing hints _Nullable and _Nonnull (indicating that the pointer may not be NULL) will optionally declare pointers as _Nullable and _Nonnull depending on which platform/compiler that is used.

Example: In zipconf.h (a platform specific include file for libzip) on Linux, you would see

#define _Nullable
#define _Nonnull

and all the zip functions will have both _Nullable and _Nonnull in their declarations. On Linux these will however be replaced with nothing thanks to the above #defines. On a platform dominated by clang or icx these definitions will not exist and the implementation specific keywords will then be passed on to the compiler as-is.

like image 119
Ted Lyngmo Avatar answered Sep 15 '25 06:09

Ted Lyngmo


The _Nullable and thus the Nonnull are hints for the programmer and the compiler tool for this variables. This allows some assumptions for the code like that checking for NULL is needed or not. Interesting this gets when you have Objective-C code and you bridge it to Swift. In that case the IDE (or the underlying compiler AI) generates different data types which leads to differnet and clearer code. I guess in some other languages it is the same.

So using this keywords is a good idea.

Tip: use some macro to redefine the value when your compiler doesnt support that feature for now.

like image 39
Karsten Avatar answered Sep 15 '25 08:09

Karsten