有没有一种方法可以在C语言中指定函数的默认参数?


当前回答

No.

即使是最新的C99标准也不支持这一点。

其他回答

不是真的。唯一的方法是编写一个varargs函数,并手动填充调用者没有传递的参数的默认值。

https://github.com/cindRoberta/C/blob/master/structure/function/default_parameter.c

#include<stdio.h>

void f_impl(int a, float b) {
  printf("%d %g\n", a, b);
}

#define f_impl(...) f_macro(__VA_ARGS__, 3.7)
#define f_macro(a, b, ...) f_impl(a, b)

int main(void) {
  f_impl(1);
  f_impl(1, 2, 3, 4);

  return 0;
}

我知道如何更好地做到这一点。 您只需将NULL赋值给一个参数,因此,您将没有值。然后检查参数值是否为NULL,将其更改为默认值。

void func(int x){
if(x == NULL)
  x = 2;
....
}

尽管如此,它还是会引起警告。一个更好的选择是,如果参数值是:

void func(int x){
if(x == 1)
  x = 2;
....
}

在上面的例子中,如果x是1,函数将其更改为2;

感谢@user904963,编辑: 如果必须覆盖所有的数字范围,那么添加另一个参数来告诉函数是否将形参设置为默认并不难

void func(int x, bool useDefault){
if(useDefault) //useDefault == true
  x = 2;
....
}

但是,请记住包含stdboolh

No.

即使是最新的C99标准也不支持这一点。

一般不会,但在gcc中,你可以使用宏将funcA()的最后一个参数设置为可选的。

在funcB()中,我使用了一个特殊的值(-1)来表示我需要'b'参数的默认值。

#include <stdio.h> 

int funcA( int a, int b, ... ){ return a+b; }
#define funcA( a, ... ) funcA( a, ##__VA_ARGS__, 8 ) 


int funcB( int a, int b ){
  if( b == -1 ) b = 8;
  return a+b;
}

int main(void){
  printf("funcA(1,2): %i\n", funcA(1,2) );
  printf("funcA(1):   %i\n", funcA(1)   );

  printf("funcB(1, 2): %i\n", funcB(1, 2) );
  printf("funcB(1,-1): %i\n", funcB(1,-1) );
}