views:

127

answers:

2

Hello,

I recently stumbled upon this page. And I was particularly interested about the section which dealt with Direct Parameter Access.

I was just wondering if there is any way to execute just one of the functions depending on the value of n in the following line:

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

where func1,.. have signature as int func1(), int func2(), and so on.. This is a restriction as I might want to have function tha return void too.

In the above line, only the address of the function is printed; The function is not called..

I even tried using the ',' (comma operator) to achieve this; but in that case, all the functions in the list will get call, and the result corresponding to the 'n' is printed.

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

Thanks.

+4  A: 

Not in a single line, but something like:

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

seems to be a start. If the functions return void, rather than int, what are you thinking of printing?

Alex Martelli
Yes! this way you can achieve that goal! But my question is how can I do that using Direct Paramter access..
Srivatsan Iyer
The answer to that is: no, you can't make `printf` invoke functions for you. Why do you care about "direct parameter access"? It's not something magical, and even if `printf` could do what you wanted, it wouldn't be any more efficient or more readable than the above solution.
jamesdlin
+1  A: 

No, you can't do this with printf as printf does not support invocation of function pointer parameters.

But, you can write your own function that does this using 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)());
}
R Samuel Klatchko