0

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;

}
4
  • how get input, using http request? Commented Sep 10, 2012 at 10:55
  • C doesn't have any "reflection" functionality. Once a program has been compiled, it can't find out name of functions or variables, or find a function or variable by name. So you have to make your program with the names built-in at compile time, as in the answer from Michael. Commented Sep 10, 2012 at 11:08
  • @JoachimPileborg, rhen how such a feature is implemented in python or php as both of them are based on C Commented Sep 11, 2012 at 14:50
  • The compilers and interpreters keep track of all structures and data themselves, it's not using any "built-in" functionality in the language they are implemented in for this. Commented Sep 11, 2012 at 15:39

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.