void f(int a, char b, char* c) {
if(..) {
...
f(a,b,c); //recursive
}
...
}
void g(int a, double b, char* c, int d) {
if(..) {
...
g(a,b,c,d); //recursive
}
...
}
我想做一个单独的函数,因为我多次使用 if
语句中的代码。但是这个函数必须有一个函数作为参数,因为我使用递归方法。我知道我们可以使用函数作为参数,但是在 f
函数中有 3 个参数,在 g
函数中有 4 个参数。
f
中的if语句中的代码与g
中的if语句中的代码相同。除了那个代码中的函数调用?
只是我不知道如何解决这个问题。
最佳答案
您可以使用 union 来打包可变数量的参数,如下面的示例代码所示。 像这样使用 union 可能不太常见,但它确实有效。
#include<stdio.h>
union u {
struct { int a; char b; char* c; } f;
struct { int a; double b; char* c; int d; } g;
};
void func_u_f (union u* ua) {
printf(" f = {a: %d, b: %c, c:%s}\n", ua->f.a, ua->f.b, ua->f.c);
ua->f.a++;
}
void func_u_g (union u* ua) {
printf(" g = {a: %d, b: %e, c:%s, d:%d}\n",
ua->g.a, ua->g.b, ua->g.c, ua->g.d);
ua->g.a++; ua->g.b *= 2.0; ua->g.d++;
}
void r (int i, void (*func) (union u*), union u* ua) {
if (i < 3) { /* or whatever conditions to terminate recursion */
printf ("Recursion %d\n", i);
func(ua);
r (++i, func, ua);
} else {
printf ("Exit recursion at %d\n", i);
return;
}
}
int main () {
union u u1, u2;
/* f */
u1.f.a = 10; u1.f.b = 'X'; u1.f.c = "I am u.f.";
r(0, &func_u_f, &u1);
/* g */
u2.g.a = 10; u2.g.b = .4e-6; u2.g.c = "I am u.g."; u2.g.d = 98;
r(-2, &func_u_g, &u2);
return 0;
}
关于c - 在 C 中作为函数参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65374193/