使用循环在C中调用"顺序"命名函数

Vla*_*r O 2 c

假设我有函数foo_1(),foo_2(),... foo_n()

我怎么能用一个循环来调用它们,就是如何将一个字符串"转换"为一个函数调用:

for (i = 0; i < n; i++)
    switch (fork()) {
        case 0:         //child process
            *COMVAR+=m;
            //call foo_i()
            exit(4);
        case -1:
            exit(5);
   }
Run Code Online (Sandbox Code Playgroud)

Gro*_*roo 6

您不能让编译器或运行时在C中自动执行此操作,但您可以手动列出函数指针并在循环中调用它们,即:

// create your function prototype, which all functions must use
typedef void(*VoidFunc)(void);

// create the array of pointers to actual functions
VoidFunc functions[] = { foo_1, foo_2, foo_3 };

// iterate the array and invoke them one by one
int main(void)
{
    for (int i = 0; i < sizeof(functions) / sizeof(*functions); i++)
    {
        VoidFunc fn = functions[i];
        fn();
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请记住,void func()这与void func(void)C中的不一样.


pmg*_*pmg 5

不.

你能做的最好的事情就是一系列函数指针

#include <stdio.h>

typedef int (*fx)(void); // fx is pointer to function taking no parameters and returning int

int foo_1(void) { printf("%s\n", __func__); return 1; }
int foo_2(void) { printf("%s\n", __func__); return 2; }
int foo_three(void) { printf("%s\n", __func__); return 3; }

int main(void) {
    fx foo[3] = { foo_1, foo_2, foo_three };
    for (int k = 0; k < 3; k++) {
        printf("foo[%d]() returns %d\n", k, foo[k]());
    }
}
Run Code Online (Sandbox Code Playgroud)

看看在ideone上运行的代码