Reputation: 1369
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?
Upvotes: 1
Views: 84
Reputation: 96053
It's not possible in general.
The closest thing you can do is to use macros to generate that sequence of if
s without having to repeat each name twice.
Upvotes: 0
Reputation: 62563
Contrary to what people say in answers and comments, it is indeed possible.
Here is a creative approach:
void
to returning const char*
.const char*
string when both arguments are null pointers.Upvotes: 2