4

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?

Community
  • 1
  • 1
ARF
  • 7,420
  • 8
  • 45
  • 72
  • 3
    Are you sure you understand what `&my_callback` does? – Alex Celeste Mar 12 '16 at 22:04
  • 2
    @Leushenko No, not at all! Hence my question. I am confused since with the use `my_callback(my_argument)` seems to be implicitly dereferenced. – ARF Mar 12 '16 at 22:07
  • You should know that 0 and NULL are not necessarily the same thing. The compiler will probably perform the needed implicit conversion, but the posted code should be using NULL, not 0 when initializing the function pointer `my_callback` – user3629249 Mar 15 '16 at 00:44
  • actually, there is quite a lot of difference, 0 is a numeric value, an `int` type. While NULL is a `void*` type, The compiler does care about the type of a value being assigned to a pointer. in most cases, the compiler will perform the necessary implicit conversion. That does not mean that it is 'ok' to write code where the compiler is having to correct the coders mistakes (when it can) via implicit conversions. – user3629249 Mar 16 '16 at 03:22

2 Answers2

10

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?

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
3

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
}
derekerdmann
  • 17,696
  • 11
  • 76
  • 110
  • I was uncertain because `my_callback` gets automatically dereferenced when I use it: `my_callback(my_argument)`. I thought this automatic dereferencing might also apply to other uses. – ARF Mar 12 '16 at 22:05
  • @ARF - You're absolutely correct. `my_callback` is a pointer, so `my_callback(my_argument)` is dereferencing that pointer and executing the function – derekerdmann Mar 12 '16 at 22:06
  • 2
    @ARF It only gets auto-dereferenced when you call it like a function with `(..)`. – HolyBlackCat Mar 12 '16 at 22:26