Home >Backend Development >C++ >How to Dynamically Invoke Functions by Name in C ?
Invoking Functions by Name in C
In C , it is often necessary to call functions by their names, especially in dynamic programming and code generation contexts. While using 'if' and 'else' for different function calls is a basic approach, it can become cumbersome for large numbers of functions.
One potential solution is reflection. However, C lacks native reflection capabilities. Alternatively, one can employ a workaround using:
An std::map of Function Pointers
By creating a map that associates function names (std::strings) with function pointers, it becomes easier to call functions dynamically:
<code class="cpp">#include <iostream> #include <map> int add(int i, int j) { return i + j; } int sub(int i, int j) { return i - j; } typedef int (*FnPtr)(int, int); int main() { // Initialization: std::map<std::string, FnPtr> myMap; myMap["add"] = add; myMap["sub"] = sub; // Usage: std::string s("add"); int res = myMap[s](2, 3); std::cout << res; }</code>
In this approach, the string key "add" retrieves the corresponding function pointer, which is then invoked with the specified arguments. This approach allows for flexible function invocation by dynamically determining the name of the function to be called.
The above is the detailed content of How to Dynamically Invoke Functions by Name in C ?. For more information, please follow other related articles on the PHP Chinese website!