c - 如何只有一些参数到函数 C

标签 c function

我有这个功能:
void func(int a, int b, char s, FILE *fp, int flag)
我想根据标志使用函数的参数。例如:
func(num, NOTHING, NOTHING, file, 1)
func(num, othernum, NOTHING, NOTHING, 2)
在函数 this_is_function 上我想要:

void func(int a, int b, char s, FILE *fp, int flag){
if(flag == 1){
/* use a and file */
}
if(flag == 2){
/* use a,b */
}
/* etc etc */
}

我想知道这是否可能以及如何做到这一点!
提前致谢:)

最佳答案

如果说 NOTHING 你的意思是你真的想忽略那个论点,我认为你概述它的方式是不可能的。

这通常在 C 中完成的方式是通过 variable argument lists .这意味着您必须重新表述,以便 flag 先行,因为它决定了其余参数:

void func(int flag, ...)
{
  va_list args;
  int num, othernum;
  FILE *file;

  va_start(args, flag);
  if(flag == 1)
  {
    num = va_arg(args, int);
    file = va_arg(args, FILE *);
  }
  else if(flag == 2)
  {
    num = va_arg(args, int);
    othernum = va_args(args, int);
  }
  va_end(args);

  /* Inspect `flag` again, and do things with the values we got. */
}

然后你可以像这样使用函数:

func(1, 42, a_file);

func(2, 17, 4711);

这当然需要非常小心,因为您不再从编译器那里获得很多帮助来将调用中提供的值与函数期望的值相匹配。

我建议将其重组为不同的顶级函数,使用适当的参数调用通用的“worker”函数:

func_mode1(42, a_file);
func_mode2(17, 4711);

然后这些可以使用适当的 flag 值调用 func(),为不适用的参数填充合适的默认值(例如 NULL 用于未使用的文件指针)。

关于c - 如何只有一些参数到函数 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11262085/

相关文章:

C 'restrict' 基于关键字的优化

c - 'typeof' 之前的预期表达式或 'typeof' 之前的预期主表达式

c - 如何捕获c中execvp()函数的输出?

c - 如何确保父进程先于子进程执行scanf()?

Javascript 定义对象属性和函数的新方法?

c - 将 "adress"作为函数参数传递 - Python 3

c - 在进程之间异步传递文件描述符

python - Pandas 聚合函数输出到 xlsx

c++ - 调用这个函数(没有定义)是如何工作的?

c++ - 来自其他类 C++ 的函数指针