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 function is called.
Without inserting any print statement in those functions, how can I come to know the name of function which the pointer currently points to?
Syntax of function pointer In the above declaration, *ip is a pointer that points to a function which returns an int value and accepts an integer value as an argument.
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.
Address of a function in C or C++ We all know that code of every function resides in memory and so every function has an address like all others variables in the program. We can get the address of a function by just writing the function's name without parentheses. Please refer function pointer in C for details.
That depends on your compiler and target environment, but most likely it points to ROM—executable code is almost always placed in read-only memory when available.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With