Call various functions using direct parameter access in C

I recently came across this page . And I was particularly interested in the section on access to direct parameters.

I'm just wondering if there is a way to execute only one of the functions depending on the value of n in the following line:

printf("%n$p", func1, func2, func3 .. funcN);

where func1, .. have a signature like int func1 (), int func2 (), etc. This is a limitation, since I might also want to have a tha return void function.

The line above prints only the address of the function; The function is not called ..

I even tried using the "," (comma operator) to achieve this; but in this case, all functions in the list will receive a call, and the result corresponding to "n" will be printed.

Is there a way to actually execute a function inside printf (..)?

Thank.

+3
source share
2 answers

No, you cannot do this with printf, because printf does not support calling function pointer parameters.

But you can write your own function that does this with stdarg:

#include <stdarg.h>

void invoke_and_print(unsigned int n, ...)
{
    va_list ap;
    va_start(ap, n);

    int (*fp)(void) = NULL;
    while (n-- != 0)
    {
        fp = va_arg(ap, int (*)(void));            
    }
    va_end(ap);

    printf("%d\n", (*fp)());
}
+2
source

Not on one line, but something like:

typedef int (*fp)();
fp[] thefuncs = {func1, func2, func3, func4};
printf("%d", fp[n]());

seems like a start. If functions return void rather than int, what do you think of printing?

+5
source

Source: https://habr.com/ru/post/1726647/


All Articles