c - 在 C 中作为函数参数的函数

标签 c function

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/

相关文章:

c - 使用 UART 检查从 SPH0645 Mic I2S 协议(protocol)接收的数据

c - 我如何在 c 中创建一个二维数组并使用指针和函数显示它?

c - “notestofile”功能不起作用

postgresql - 从多个表中的多个列中获取 ID 作为一组或数组

python - 硬件问题 : Is it possible to convert all the test scores without additional blocks in grading function?

python - 导入同名函数会覆盖吗?

c - 如何将首字母转换为大写?

c++ - 为什么编译时间的持续时间至关重要?

c管道为什么是fd[0]和fd[1] 3和4

javascript - 动态修改 JavaScript 中的构造函数?