Determining to which function a pointer is pointing in C?

后端 未结 9 1004
情话喂你
情话喂你 2021-02-01 12:25

I have a pointer to function, assume any signature. And I have 5 different functions with same signature.

At run time one of them gets assigned to the pointer, and that

9条回答
  •  星月不相逢
    2021-02-01 13:14

    To know where a function pointer points is something you'll have to keep track of with your program. Most common is to declare an array of function pointers and use an int variable as index of this array.

    That being said, it is nowadays also possible to tell in runtime which function that is currently executed, by using the __func__ identifier:

    #include 
    
    typedef const char* func_t (void);
    
    const char* foo (void)
    {
      // do foo stuff
      return __func__;
    }
    
    const char* bar (void)
    {
      // do bar stuff
      return __func__;
    }
    
    int main (void)
    {
      func_t* fptr;
    
      fptr = foo;
      printf("%s executed\n", fptr());
    
      fptr = bar;
      printf("%s executed\n", fptr());
    
      return 0;
    }
    

    Output:

    foo executed
    bar executed
    

提交回复
热议问题