Home > database >  Checking whether function pointer is assigned value or not in a particular situation
Checking whether function pointer is assigned value or not in a particular situation

Time:01-02

I have a structure in my cpp program. Function pointer is one of its members. When this structure is passed to a function-in-dll, it assigns a function to this pointer. So my main program does not know if the dll has assigned a function or not. My aim is to call the function through pointer only if it is assigned through dll. I have made a minimal-working code of the situation:

#include <stdio.h>
typedef struct _test{
        void (*foo)(int a){};
}test;
void bar(int b)
{
        printf("you called bar\n");
}
int main()
{
        test _a;
        test* a=&_a;
        if(a->foo)printf("OK");
        else printf("ELSE");

        a->foo=bar;

        if(a->foo)printf("OK2");
        else printf("ELSE2");
        return 1;
}

The output i get when running is

ELSEOK2

The output is consistent with my expectations. I want know whether i can use

if(a->foo)

to check the situation, so that in future it will not lead to errors. Also is it right to do curly braces { } in end of function pointer

void (*foo)(int a){};

without which i cannot check if foo->a is not zero.

CodePudding user response:

void (*foo)(int a){}; does initialization to nullptr.

It is equivalent to

void (*foo)(int a) = nullptr;

and

if (a->foo) (or if (a->foo != nullptr)) is correct way to check is pointer is not nullptr.

  •  Tags:  
  • c
  • Related