Search code examples
cfunction-pointers

How to write the name of a function using a function pointer?


I have this code with an array of function pointers that represents a sequence of functions, and I want to display the function names like this:

static void print_sequence(t_op_sequence *seq)
{
    int i;

    i = -1;
    while (++i < seq->size)
    {
        if (seq->sequence[i] == pa)
            ft_putendl("pa");
        else if (seq->sequence[i] == pb)
            ft_putendl("pb");
        else if (seq->sequence[i] == sa)
            ft_putendl("sa");
        else if (seq->sequence[i] == sb)
            ft_putendl("sb");
        else if (seq->sequence[i] == ss)
            ft_putendl("ss");
        else if (seq->sequence[i] == ra)
            ft_putendl("ra");
        else if (seq->sequence[i] == rb)
            ft_putendl("rb");
        else if (seq->sequence[i] == rr)
            ft_putendl("rr");
        else if (seq->sequence[i] == rra)
            ft_putendl("rra");
        else if (seq->sequence[i] == rrb)
            ft_putendl("rrb");
        else if (seq->sequence[i] == rrr)
            ft_putendl("rrr");
    }
}

The t_op_sequence struct containing a flexible function pointer array:

typedef void    (*t_operation)(t_stack *, t_stack *);

typedef struct  s_op_sequence
{
    size_t      size;
    t_operation sequence[];
}   t_op_sequence;

There is no problem with my code but I'd like to do it without all the if/else or switch statements. I know that inside a function you can use __func__ or __FUNCTION__ to get the function's name, but is there a trick to do the same but using function pointers, so outside of the function itself?


Solution

  • Contrary to what people say in answers and comments, it is indeed possible.

    Here is a creative approach:

    • Change your function signature from returning void to returning const char*.
    • Change the functions themselves to return their name as const char* string when both arguments are null pointers.
    • Call the functions with null pointers as arguments
    • Profit!