Anubhav Agarwal
Anubhav Agarwal

Reputation: 2062

How can I implement Php call_user_func in C

There is function in php call_user_func() which takes in argument a string name, and callbacks a function with similar name. Similarly I want to do in C. I want to write a program which prompts user for min or max, and calls the function min or max depending on the string entered by user. I tried the following but did not work for obvious reasons. Can anyone suggest the corrections I need to make

int max(int a, int b)
{
    return a > b ? a : b ;
}

int min(int a, int b)
{
    return a < b ? a : b ;
}

int main()
{
    int (*foo)(int a, int b);
    char *str;
    int a, b;
    str = (char  *)malloc(5);
    printf("Enter the what you want to calculate min or max\n");
    scanf("%s", str);
    printf("Enter the two values\n");
    scanf("%d %d", &a, &b);

    foo = str;

    printf("%d\n", (*foo)(a, b));
    return 0;

}

Upvotes: 0

Views: 182

Answers (1)

Michael
Michael

Reputation: 58507

Try something like this:

int max(int a, int b)
{
    return a > b ? a : b ;
}

int min(int a, int b)
{
    return a < b ? a : b ;
}

typedef struct {
    int (*fp)(int, int);
    const char *name;
} func_with_name_t;

func_with_name_t functions[] = {
    {min, "min"},
    {max, "max"},
    {NULL, NULL}    // delimiter   
};

int main()
{
    char *str;
    int a, b, i;
    str = (char  *)malloc(5);
    printf("Enter the what you want to calculate min or max\n");
    scanf("%s", str);
    printf("Enter the two values\n");
    scanf("%d %d", &a, &b);

    for (i = 0; functions[i].name != NULL; i++) {
        if (!strcmp(str, functions[i].name)) {
            printf("%d\n", functions[i].fp(a, b));
            break;
        }
    }

    return 0;
}

Upvotes: 1

Related Questions