I don't know how to accomplish this!
how to get the function pointer in va_list arguments?
thanks so much.
2 Answers
Typedefs often make working with function pointers easier, but are not necessary.
#include <stdarg.h>
void foo(int count, ...) {
va_list ap;
int i;
va_start(ap, count);
for (i = 0; i < count; i++) {
void (*bar)() = va_arg(ap, void (*)());
(*bar)();
}
va_end(ap);
}
5 Comments
caf
In general, to create a type name (for use with
va_arg, sizeof, a typecast or similar), write a declaration of a variable with that type, then remove the variable name.Robert Gamble
Actually, this is (ironically) they only time that typedefs are required. Speaking of the type parameter for va_arg in section 7.15.1.1 of the C Standard: "The parameter type shall be a type name specified such that the type of a pointer to an object that has the specified type can be obtained simply by postfixing a * to type." This means that many non-trivial types aren't guaranteed to work, including your example, without a typedef.
KeatsPeeks
Doesn't compile on my toolset.
ephemient
Yeah, a couple hours after I wrote this I thought about whether it was legal, and then "well, it works with GCC..." Oh well, caf's comment is useful regardless of this particular answer.
caf
...except strike
va_arg from the examples I gave.