Skip to content

Instantly share code, notes, and snippets.

@gooooloo
Created November 12, 2019 02:33
Show Gist options
  • Save gooooloo/6547c91edf2f1da8fca460985037c134 to your computer and use it in GitHub Desktop.
Save gooooloo/6547c91edf2f1da8fca460985037c134 to your computer and use it in GitHub Desktop.
可变长函数指针
#include <stdio.h>
#include <stdarg.h>
typedef void (*f_type)(int, ...);
void foo1(int n1) { printf("%d\n", n1); }
void foo2(int n1, int n2) { printf("%d %d\n", n1, n2); }
void foo3(int n1, int n2, int n3) { printf("%d %d %d\n", n1, n2, n3); }
void bar(f_type pf, ...) {
if ((void *)pf == (void *)foo1) {
va_list args;
va_start(args, pf);
int n1 = va_arg(args, int);
va_end(args);
foo1(n1);
} else if ((void *)pf == (void *)foo2) {
va_list args;
va_start(args, pf);
int n1 = va_arg(args, int);
int n2 = va_arg(args, int);
va_end(args);
foo2(n1, n2);
} if ((void *)pf == (void *)foo3) {
va_list args;
va_start(args, pf);
int n1 = va_arg(args, int);
int n2 = va_arg(args, int);
int n3 = va_arg(args, int);
va_end(args);
foo3(n1, n2, n3);
}
}
int main(int, char**) {
int a=3, b=4, c=5;
bar((f_type)foo1, a);
bar((f_type)foo2, a, b);
bar((f_type)foo3, a, b, c);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment