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


当前回答

是的。:-)但不是你所期望的那样。

int f1(int arg1, double arg2, char* name, char *opt);

int f2(int arg1, double arg2, char* name)
{
  return f1(arg1, arg2, name, "Some option");
}

不幸的是,C不允许重载方法,因此最终会得到两个不同的函数。尽管如此,通过调用f2,你实际上是在用默认值调用f1。这是一个“不要重复自己”的解决方案,它可以帮助您避免复制/粘贴现有代码。

其他回答

做到这一点的最好方法(根据你的情况,这可能也可能不可能)可能是转移到c++,并将其作为“更好的C”使用。你可以在不使用类、模板、操作符重载或其他高级特性的情况下使用c++。

这将为您提供一个具有函数重载和默认参数(以及您选择使用的任何其他特性)的C变体。如果你真的想只使用c++的一个受限子集,你就必须稍微自律一些。

很多人会说以这种方式使用c++是一个糟糕的想法,他们可能是有道理的。但这只是一种观点;我认为使用c++中你觉得舒服的特性是合理的,而不必购买整个东西。我认为c++成功的一个重要原因是它在早期被大量的程序员以这种方式使用。

我们可以为默认值创建(仅)使用命名形参的函数。这是bk.答案的延续。

#include <stdio.h>                                                               

struct range { int from; int to; int step; };
#define range(...) range((struct range){.from=1,.to=10,.step=1, __VA_ARGS__})   

/* use parentheses to avoid macro subst */             
void (range)(struct range r) {                                                     
    for (int i = r.from; i <= r.to; i += r.step)                                 
        printf("%d ", i);                                                        
    puts("");                                                                    
}                                                                                

int main() {                                                                     
    range();                                                                    
    range(.from=2, .to=4);                                                      
    range(.step=2);                                                             
}    

C99标准定义了初始化中后面的名称覆盖前面的项。我们也可以有一些标准的位置参数,只是相应地改变宏和函数的签名。默认值参数只能在命名参数样式中使用。

项目输出:

1 2 3 4 5 6 7 8 9 10 
2 3 4 
1 3 5 7 9

你不需要只在c上使用VARARGS,下面是一个例子。

int funcA_12(int a1, int a2) { ... }

#define funcA(a1) funcA_12(a1, 0)

这个答案与上面的两个函数方法非常相似,但在这种情况下,您使用的是定义参数的函数名宏。

一般不会,但在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) );
}

OpenCV使用的是:

/* in the header file */

#ifdef __cplusplus
    /* in case the compiler is a C++ compiler */
    #define DEFAULT_VALUE(value) = value
#else
    /* otherwise, C compiler, do nothing */
    #define DEFAULT_VALUE(value)
#endif

void window_set_size(unsigned int width  DEFAULT_VALUE(640),
                     unsigned int height DEFAULT_VALUE(400));

如果用户不知道他应该写什么,这个技巧会很有用: