Following on from this excellent SO answer on function pointers; given a function pointer defined in C like:
typedef void (*Callback)(int argument);
Callback my_callback = 0;
how do I check whether the callback function pointer has been assigned a non-null value?
my_callback == 0
or &my_callback == 0
?
You should check for my_callback == 0
since it's a function pointer.
Moreover, the second option you are thinking of:
&my_callback == 0
is the address and you will even been warned by the compiler:
warning: the comparison will always evaluate as ‘false’ for the address of ‘my_callback’ will never be NULL [-Waddress]
if(&my_callback == 0)
^
Is NULL always zero in C?
Remember that the type of the variable is a function pointer, so you can compare it directly against NULL
or 0
.
It might depend on your coding convention and style preferences, but I tend to use the pointer as the boolean value itself:
if (my_callback) {
// Do the thing
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With