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


当前回答

其他回答

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

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));

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

No.

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

不,但你可以考虑使用一组函数(或宏)来近似使用默认参数:

// No default args
int foo3(int a, int b, int c)
{
    return ...;
}

// Default 3rd arg
int foo2(int a, int b)
{
    return foo3(a, b, 0);  // default c
}

// Default 2nd and 3rd args
int foo1(int a)
{
    return foo3(a, 1, 0);  // default b and c
}

简单的回答:不。

稍微长一点的回答:有一个很老很老的解决方法,你传递一个字符串来解析可选参数:

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

哪里的opt可能包括“name=value”对或其他东西,你会叫喜欢吗

n = f(2,3.0,"foo","plot=yes save=no");

显然,这只是偶尔有用。一般来说,当你想要一个单一的接口到一系列功能时。


你仍然可以在专业程序用c++编写的粒子物理代码中找到这种方法(例如ROOT)。它的主要优点是可以几乎无限期地扩展,同时保持向后兼容性。