ARF
ARF

Reputation: 7684

Checking typedef defined function pointer for null

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?

Upvotes: 4

Views: 6338

Answers (2)

gsamaras
gsamaras

Reputation: 73366

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?

Upvotes: 10

derekerdmann
derekerdmann

Reputation: 18252

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
}

Upvotes: 3

Related Questions