Determining to which function a pointer is pointing in C? Determining to which function a pointer is pointing in C? c c

Determining to which function a pointer is pointing in C?


You will have to check which of your 5 functions your pointer points to:

if (func_ptr == my_function1) {    puts("func_ptr points to my_function1");} else if (func_ptr == my_function2) {    puts("func_ptr points to my_function2");} else if (func_ptr == my_function3) {    puts("func_ptr points to my_function3");} ... 

If this is a common pattern you need, then use a table of structs instead of a function pointer:

typedef void (*my_func)(int);struct Function {    my_func func;    const char *func_name;};#define FUNC_ENTRY(function) {function, #function}const Function func_table[] = {    FUNC_ENTRY(function1),    FUNC_ENTRY(function2),    FUNC_ENTRY(function3),    FUNC_ENTRY(function4),    FUNC_ENTRY(function5)}struct Function *func = &func_table[3]; //instead of func_ptr = function4;printf("Calling function %s\n", func->func_name);func ->func(44); //instead of func_ptr(44);


Generally, in C such things are not available to the programmer.

There might be system-specific ways of getting there by using debug symbols etc., but you probably don't want to depend on the presence of these for the program to function normally.

But, you can of course compare the value of the pointer to another value, e.g.

if (ptr_to_function == some_function)    printf("Function pointer now points to some_function!\n");


The function names will not be available at runtime.

C is not a reflective language.

Either maintain a table of function pointers keyed by their name, or supply a mode of calling each function that returns the name.