Using a loop to call 'sequentially' named functions in C

Viewed 227

Say I have functions foo_1(), foo_2(),...foo_n()

How could I use a loop to call them, that is how could 'convert' a string to a function call:

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

You cannot have the compiler or runtime do this automatically in C, but you can manually list the function pointers and invoke them in a loop, i.e.:

// 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;
}

Keep in mind that void func() is not the same as void func(void) in C.

Nope.

The best you can do involves an array of function pointers

#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]());
    }
}

see code running on ideone

Generally , your approach isn't possible in C. But you can do it by using switch statement. Though you have to write little bit of code.

switch (n)
​{
    case 1:
        foo_1();
        break;

    case 2:
        foo_2();
        break;
    case 3:
        foo_3();
        break;
        .
        .
        .
    case n:
        foo_n();
        break;
    default:
        // code to be executed if n doesn't match any constant
}

Higher level languages that have reflection such as Java is able to do such kind of operations, but C does not. In Java, you can do something like below:

You have a class named MyClass

public class MyClass {
    public void myMethodName(String arg1);
}

You can use below flow to call myMethodName using String form.

Class myObject = new MyClass();
Class<?> c = Class.forName("MyClass");
Class[] argTypes = new Class[] { String[].class };
Method method = c.getDeclaredMethod("myMethodName", argTypes);
method.invoke(myObject, params);

Here is the official document: https://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html

Related